Victor Jeman Academy
Python Fundamentals8 min

Dictionaries

Store and manipulate labelled key-value data with dictionaries, plus zip and sorted as tools for working with them.

What You'll Learn

  • Create and manipulate dictionaries with key-value pairs
  • Access, modify, and remove keys with get(), del, and pop()
  • Iterate over dictionaries with for and the items() method
  • Build and sort dictionaries with zip() and sorted()

In this lesson:

  • Build a dictionary of key-value pairs so related data lives in one labelled object
  • Read, change, and remove keys with [], get(), del, and pop()
  • Walk a dictionary with a for loop and items()
  • Turn your hero into a single dictionary (the shape the rest of the game will use)

Last lesson your functions were passing eight values around: name, hp, attack, defense, gold, and on and on. That gets ugly fast, and you felt it. A dictionary fixes it. It stores related data as key-value pairs, so your hero becomes one object with labelled fields instead of eight loose variables.

This lesson is the first of three that finish the Python Kingdom. We'll learn dictionaries on small creature stat cards (Flamarion, Aquadon) because they're easy to picture, then turn your own hero into a dictionary at the end. Next lesson you save that hero to disk, and the one after wires in random encounters and stops the crashes. Let's start with the data structure everything else rests on.

What are dictionaries

Variabile separate vs Dictionar
Fara dictionar (4 variabile separate)
creatura_nume = "Flamarion"
creatura_tip = "foc"
creatura_hp = 95
creatura_atac = 28
Daca ai 10 creaturi = 40 de variabile!
Cu dictionar (1 singura variabila)
creatura = {
"nume": "Flamarion",
"tip": "foc",
"hp": 95,
"atac": 28
}
Totul grupat intr-un singur loc!
apasa pe un camp ca sa vezi cum se acceseaza in ambele variante

A dictionary is a collection of key-value pairs. Picture a creature's stat card: the label on the left (name, type, HP), the value on the right.

You create a dictionary using curly braces {}:

Result:

text
{'name': 'Flamarion', 'type': 'fire', 'hp': 95, 'attack': 28}

Each element in the dictionary has two parts separated by :, the key (on the left) and the value (on the right). Keys are usually strings, and values can be anything: strings, numbers, lists, even other dictionaries.

You can also create an empty dictionary and add elements as you go:

Result:

text
{'name': 'Aquadon', 'type': 'water', 'hp': 110, 'attack': 22}

Accessing and modifying values

To get a value from a dictionary, you use the key inside square brackets:

Result:

text
Creature name: Flamarion
Hit points: 95

If you try to access a key that does not exist, you get a KeyError. To avoid that, you can use the get() method, which returns None (or a default value) if the key is missing:

Result:

text
Speed: 0

You can modify values the same way you set them initially:

Result:

text
HP before battle: 95
HP after battle: 65
Attack after evolution: 42

Removing keys (del and pop)

Setting and reading keys is half the job. You also need to remove them, say a creature drops a buff or you strip a temporary stat. There are two ways.

del removes a key completely:

Result:

text
Before: {'name': 'Flamarion', 'type': 'fire', 'hp': 95, 'attack': 28}
After del: {'name': 'Flamarion', 'hp': 95, 'attack': 28}

pop() removes the key and hands you back the value it deleted. Reach for it when you still need that value:

Result:

text
Saved HP: 110
Remaining dictionary: {'name': 'Aquadon', 'type': 'water', 'attack': 22}

With pop() you can pass a default, so a missing key returns the default instead of crashing:

Result:

text
Ability: none

Iterating over dictionaries

When you want to display all the information about a creature, you use a for loop. The items() method gives you access to each key-value pair:

Result:

text
=== Creature Stat Card ===
name : Terravolt
type : earth
hp : 130
attack : 35

You can also iterate over just the keys or just the values:

Result:

text
name
type
hp
attack

---

Terravolt
earth
130
35

You can check if a key exists in a dictionary with the in operator:

Result:

text
The creature has 130 hit points.
We do not know this creature's speed.

The zip() function

Optional deep-dive. Skip the zip and sorted sections if you just want the basics; the game doesn't depend on them.

Cum functioneaza zip()
perechi = list(zip(nume_creaturi, tipuri))
nume_creaturi=[
"Flamarion"
"Aquadon"
"Terravolt"
]
tipuri=[
"foc"
"apa"
"pamant"
]
zip()
apasa "Ruleaza" ca sa vezi cum se combina listele

Imagine you have two separate lists: one with creature names and one with their types. The zip() function combines them into pairs, like a zipper joining two sides:

Result:

text
[('Flamarion', 'fire'), ('Aquadon', 'water'), ('Terravolt', 'earth')]

You can feed that straight into dict() to build a dictionary in one line:

Result:

text
{'Flamarion': 'fire', 'Aquadon': 'water', 'Terravolt': 'earth'}

Two parallel lists become one dictionary, no loop required.

The sorted() function

The sorted() function returns a sorted version of a list, without modifying the original list:

Result:

text
Original: [12, 5, 23, 8, 17, 3]
Sorted: [3, 5, 8, 12, 17, 23]
Descending: [23, 17, 12, 8, 5, 3]

It also works with strings, sorting them in alphabetical order:

Result:

text
Alphabetical order: ['Aquadon', 'Breezel', 'Flamarion', 'Terravolt']

You can also sort the keys of a dictionary:

Result:

text
Creatures sorted by name:
Aquadon: 110 HP
Flamarion: 95 HP
Terravolt: 130 HP

Exercise : Enemy database

Create a dictionary for a monster called "Goblin" with the keys: "name", "hp", "attack", and "gold_reward". Then create a second dictionary for "Dark Bug" (the final boss) with higher stats. Display both enemies' stat cards using a for loop with .items().

Exercise : Contact book

Write a program that lets the user manage a contact book using a dictionary. The user can: (1) Add a contact (name as key, phone as value), (2) Search for a contact by name, (3) Display all contacts, (4) Exit. Use a while True loop with a menu.

Exercise : Bestiary from two lists (zip + sorted)

You have two parallel lists: creature names and their HP values. Use zip() to pair them, dict() to build one dictionary, then print each creature on its own line in alphabetical order with sorted(). This is the optional zip/sorted deep-dive in action.

Your game grows: the hero is now a dictionary

The creatures were practice. Here's the payoff for your own game: the hero you've carried since lesson 1, eight loose variables until now, becomes one tidy dictionary. This is the exact shape every later lesson builds on.

Next lesson you save this dictionary to a file, so closing the window no longer wipes your hero.

Next: make it survive

A creature is now one tidy object instead of eight loose variables. But there's a catch you've lived with this whole course: the moment the program ends, that object is gone. Close the window and your perfectly built dictionary evaporates.

Next lesson, Files and saving data, you'll write that object to disk so it survives after the program closes. That's a save game.

Test Your Knowledge

Check how well you understood the lesson with these 2 questions.

Question 1 of 2

How do you access the value for the key "hp" in the creature dictionary?