Skip to content

Dictionaries: keys, values and .get()

BeginnerLesson 6 of 146 min

Look things up by name with Python dictionaries: add and change values, avoid KeyError with .get() and a default, and loop over keys and values with .items().

A list finds things by position. A dictionary (a dict) finds them by a key you choose, usually a string:

capitals = {"Kenya": "Nairobi", "Peru": "Lima", "Laos": "Vientiane"}
print(capitals["Peru"])   # Lima
print(len(capitals))      # 3

Each entry is key: value. Keys are unique: one value per key.

Adding and changing

Assigning to a key adds it, or replaces the value if it's there already:

fridge = {"milk": 1, "eggs": 6}
fridge["butter"] = 1     # new key
fridge["eggs"] = 4       # new value for an old key
fridge["milk"] += 1      # same as fridge["milk"] = fridge["milk"] + 1
print(fridge)            # {'milk': 2, 'eggs': 4, 'butter': 1}

A dict remembers the order its keys were first added in, which is why butter comes last.

Missing keys

Asking for a key that isn't there stops the program with a KeyError. When a key may be missing, use .get(): it gives None, or the default you pass, instead.

fridge = {"milk": 2, "eggs": 4}
print(fridge.get("jam"))     # None
print(fridge.get("jam", 0))  # 0
print("jam" in fridge)       # False: in looks at the keys

Looping

A for loop over a dict gives you its keys. .items() gives you each key with its value, and you can name both:

fridge = {"milk": 2, "eggs": 4}
for food, amount in fridge.items():
    print(f"{food}: {amount}")

(The next lesson explains for properly; here it runs the indented line once per entry.)

More in the Python docs: dictionaries in the tutorial and dict methods.

Your turn

stock counts the plants in a shop. Add an "orchid" with a count of 3, and sell one ivy (so it drops to 6). Make mint the stock of "mint" using .get() with a default of 0 (the shop has none). Then loop over .items() and print each plant with its count on its own line, like fern: 4.

Next →