3b. Dictionaries
A list holds things in order, and you reach them by their position number (0, 1, 2…). A dictionary is different: it holds pairs of a label and a value, and you reach a value by its label.
Think of a real dictionary: you look up a word (the label) to find its meaning (the value). In Python we call the label a key.
key β value. That’s the whole idea. Every value has a key you use to find it.
Making a dictionary
Use curly brackets { }. Each pair is written key: value, with commas between the pairs.
Output:
Here the keys are "name", "energy" and "speed". This is a tidy way to keep all of one creature’s information together in a single box.
An empty dictionary
Just like with lists, you can start empty and fill it up later:
Looking up a value
Use square brackets with the key (not a number!) to get its value:
Output:
This reads nicely out loud: “get the energy of the creature”.
Adding or changing a value
Put a value into a key with =. If the key already exists, it gets changed. If it doesn’t exist yet, it gets added.
Output:
You can do maths on a value too, just like with variables:
What if the key isn’t there?
If you ask for a key that doesn’t exist, Python crashes with a KeyError:
There are two safe ways to avoid this.
1. Check first with in β this asks “is this key in the dictionary?” and gives back True or False:
Output:
2. Use .get() β this looks up a key but, instead of crashing, hands back None (meaning “nothing”) if the key is missing. You can also give it a backup value to use instead:
Output:
How many pairs? Removing pairs
len() tells you how many keyβvalue pairs there are:
Remove a pair with del:
Going through a dictionary
You can loop over a dictionary, just like a list. There are three handy ways.
Loop over the keys (this is what you get by default):
Output:
Loop over the values with .values():
Output:
Loop over both at once with .items() β this gives you the key and the value together each time round:
Output:
Dictionary or list β which should I use?
- Use a list when you have lots of similar things in an order, and position is what matters β like all your creatures.
- Use a dictionary when each value has a name/label, and you want to look things up by that label β like one creature’s stats.
They team up brilliantly: you can have a list of dictionaries, where each dictionary describes one creature.
Output:
(Notice the quotes swapped to 'name' inside the f-string, because the f-string already uses " on the outside. Either quote works in Python, as long as you don’t clash.)
A peek ahead: on page 8 you’ll meet classes, which are an even tidier way to describe a creature β especially when you want it to do things (move, eat) as well as hold information. A dictionary is the simple version; a class is the upgrade. Both are worth knowing.
Super useful for evolution: counting things
Here’s a pattern you’ll want in your sim. Say you want to count how many creatures are each colour, to see which colour is winning over time. A dictionary makes this easy β use each colour as a key, and count up:
Output:
Now you can see at a glance: 3 green, 2 brown. Run this each generation and you can watch which traits are taking over. That’s evolution you can measure! π±
β Quick recap
- A dictionary stores key β value pairs:
{"name": "Spike", "energy": 100}. - Look up a value by its key:
creature["energy"]. - Add or change with
creature["energy"] = 80. - Asking for a missing key crashes β use
if key in creature:orcreature.get(key)to stay safe. len()counts the pairs;del creature["speed"]removes one.- Loop with
for key in creature,.values(), or.items()for both. - Use a list for many things in order, a dictionary for named values you look up.