← Python lessons

Dictionaries

A dictionary stores pairs: each key maps to a value. You look things up by key instead of by position, which makes it perfect for "this name has this score" style data.

Making a dictionary

banked = {"Alice": 30, "Bob": 55}

Curly braces, with key: value pairs separated by commas. Here the names are keys and the amounts are values.

Looking up a value

Put the key in square brackets:

banked = {"Alice": 30, "Bob": 55}
print(banked["Alice"])

Looking up a key that isn't there raises an error.

Check whether a key exists

in and not in check dictionary keys, not values. Check membership before a lookup when the key might be missing.

colours = {"sky": "blue", "grass": "green"}
print("sky" in colours)
print("blue" in colours)
name = "sand"
if name in colours:
    print(colours[name])
else:
    print("No colour recorded")

This prints True, False, then No colour recorded. Looking up colours["sand"] without the check would raise KeyError.

Values and length

banked = {"Alice": 30, "Bob": 55}
print(sum(banked.values()))
print(len(banked))

.values() supplies the values, so the first line prints their sum, 85. len() counts entries, so the second line prints 2.

Updating and counting

Assign to a key to add a new entry or replace its value. .get(key, default) reads a value, using the default when the key is missing:

outcomes = {}
for result in ["win", "loss", "win"]:
    outcomes[result] = outcomes.get(result, 0) + 1
print(outcomes)

On the first "win", the key is missing, so .get("win", 0) supplies 0. Later occurrences read and increase the stored count. This pattern can count any repeated category, including words.

A missing key's default is only returned by .get(); .get() does not insert that key. The assignment on the left creates or updates the entry. Updating an existing value does not move its key in dictionary order.

Looping over keys

Looping over a dictionary visits its keys in insertion order. Look up each key to read its value:

scores = {"Alice": 30, "Bob": 55}
for name in scores:
    print(name, scores[name])

Values can be any type

A dictionary value can also be a list or None. For example, {"scores": [3, 5], "best": None} stores a list under "scores" and uses None under "best" to mean that no best value has been selected yet. The meaning of None is a convention you define for your program.

A dictionary can mix numbers, text, and booleans in its values:

player = {"name": "Alice", "score": 38, "done": False}
print(player["name"])
print(player["done"])

See also: Nested data, For loops.

Your turn

Add two lines: print Bob's banked amount, then print whether "Cara" is a key in the dictionary.

banked = {"Alice": 30, "Bob": 55}
# add two prints: Bob's amount, then the "Cara" membership check

Expected output

55
False

Practise this in the free Python course, where every exercise checks your code instantly.