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.

creature = {
    "name": "Spike",
    "energy": 100,
    "speed": 5,
}
print(creature)

Output:

{'name': 'Spike', 'energy': 100, 'speed': 5}

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:

creature = {}

Looking up a value

Use square brackets with the key (not a number!) to get its value:

creature = {"name": "Spike", "energy": 100, "speed": 5}

print(creature["name"])     # Spike
print(creature["energy"])   # 100

Output:

Spike
100

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.

creature = {"name": "Spike", "energy": 100, "speed": 5}

creature["energy"] = 80        # change an existing value
creature["colour"] = "green"   # add a brand new key

print(creature)

Output:

{'name': 'Spike', 'energy': 80, 'speed': 5, 'colour': 'green'}

You can do maths on a value too, just like with variables:

creature = {"name": "Spike", "energy": 100, "speed": 5}
creature["energy"] -= 20       # take 20 energy away
print(creature["energy"])      # 80

What if the key isn’t there?

If you ask for a key that doesn’t exist, Python crashes with a KeyError:

creature = {"name": "Spike", "energy": 100}
print(creature["colour"])      # πŸ’₯ KeyError: there is no "colour" key!

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:

creature = {"name": "Spike", "energy": 100}

if "colour" in creature:
    print(creature["colour"])
else:
    print("This creature has no colour set.")

Output:

This creature has no colour set.

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:

creature = {"name": "Spike", "energy": 100}

print(creature.get("colour"))            # None β€” but no crash
print(creature.get("colour", "grey"))    # grey β€” the backup value

Output:

None
grey

How many pairs? Removing pairs

len() tells you how many key–value pairs there are:

creature = {"name": "Spike", "energy": 100, "speed": 5}
print(len(creature))     # 3

Remove a pair with del:

creature = {"name": "Spike", "energy": 100, "speed": 5}
del creature["speed"]
print(creature)          # {'name': 'Spike', 'energy': 100}

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):

creature = {"name": "Spike", "energy": 100, "speed": 5}

for key in creature:
    print(key)

Output:

name
energy
speed

Loop over the values with .values():

creature = {"name": "Spike", "energy": 100, "speed": 5}

for value in creature.values():
    print(value)

Output:

Spike
100
5

Loop over both at once with .items() β€” this gives you the key and the value together each time round:

creature = {"name": "Spike", "energy": 100, "speed": 5}

for key, value in creature.items():
    print(f"{key} = {value}")

Output:

name = Spike
energy = 100
speed = 5

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.

creatures = [
    {"name": "Spike", "energy": 100, "speed": 5},
    {"name": "Bramble", "energy": 80, "speed": 3},
]

for creature in creatures:
    print(f"{creature['name']} has {creature['energy']} energy.")

Output:

Spike has 100 energy.
Bramble has 80 energy.

(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:

creature_colours = ["green", "green", "brown", "green", "brown"]

colour_counts = {}
for colour in creature_colours:
    if colour in colour_counts:
        colour_counts[colour] += 1     # seen before β€” add one
    else:
        colour_counts[colour] = 1      # first time β€” start at one

print(colour_counts)

Output:

{'green': 3, 'brown': 2}

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: or creature.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.