← All lessons
Programming basics · Lesson 8 of 9

Dictionaries

A list finds things by position. A dictionary finds them by a key you choose, like a word in a real dictionary. It's written with curly brackets and pairs of key: value.

ages = {"Ana": 12, "Sam": 14}
print(ages["Sam"])
ages["Lee"] = 11
ages["Ana"] = 13
print(len(ages))
Prints
14
3

Setting d[key] = value adds the key if it's new, or replaces its value if it's already there; each key appears only once. Asking for a key that isn't there is a KeyError. To be safe, check with key in d first, or use d.get(key, default), which gives the default instead of an error.

Dictionaries are perfect for counting. Go through the items and add 1 to each one's count, starting it at 0 the first time.

counts = {}
for letter in "banana":
    counts[letter] = counts.get(letter, 0) + 1
print(counts)
Prints
{'b': 1, 'a': 3, 'n': 2}

To go through a dictionary, for key in d gives the keys, and for key, value in d.items() gives both. Keys are usually strings or numbers; values can be anything, even lists or other dictionaries.

Practice

What does this print?

stock = {"apples": 5, "pears": 2}
stock["pears"] = stock["pears"] + 3
print(stock["pears"])
More info

Quick reference

{k: v, …}A dictionary of keys and values.
d[k]The value for key k (KeyError if missing).
d[k] = vAdds or replaces.
d.get(k, default)The value, or the default if k is missing.
k in dTrue if the key is there.
d.items()Key and value pairs, for loops.

The other computer science courses