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, andpop() - Walk a dictionary with a
forloop anditems() - 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
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:
{'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:
{'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:
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:
Speed: 0
You can modify values the same way you set them initially:
Result:
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:
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:
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:
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:
=== Creature Stat Card ===
name : Terravolt
type : earth
hp : 130
attack : 35
You can also iterate over just the keys or just the values:
Result:
name
type
hp
attack
---
Terravolt
earth
130
35
You can check if a key exists in a dictionary with the in operator:
Result:
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.
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:
[('Flamarion', 'fire'), ('Aquadon', 'water'), ('Terravolt', 'earth')]
You can feed that straight into dict() to build a dictionary in one line:
Result:
{'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:
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:
Alphabetical order: ['Aquadon', 'Breezel', 'Flamarion', 'Terravolt']
You can also sort the keys of a dictionary:
Result:
Creatures sorted by name:
Aquadon: 110 HP
Flamarion: 95 HP
Terravolt: 130 HP
Exercise : Enemy database
Exercise : Contact book
Exercise : Bestiary from two lists (zip + sorted)
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.

