Dictionaries: keys, values and .get()
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)) # 3Each 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 keysLooping
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.
Your task
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.
- There are 3 orchids (not done yet)
- Ivy is down to 6 (not done yet)
- mint is 0, from .get() with a default (not done yet)
- Print every plant and its count, using .items() (not done yet)
The checklist ticks itself off as you work in the editor: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
{key: value}- A dict: values looked up by key; keys are unique and kept in the order added Python docs →
d[key]- The value for a key (KeyError if it’s missing). d[key] = v adds or replaces it Python docs →
.get()- d.get(key, default): the value, or the default (None if not given) when the key is missing Python docs →
.items()- Each key with its value: for key, value in d.items(): Python docs →
KeyError- Raised when a dict doesn’t have the key you asked for Python docs →