Lesson 13 · 13 of 20
Dictionaries · Python
Store key-value pairs in a Python dictionary: a greengrocer's stock with get(), del, items(), keys() and values().

A dictionary links keys to values, between braces: {"apples": 12, "pears": 5}. Instead of looking things up by position, as in a list, you look them up by key: stock["apples"] gives 12.
Changing a value and adding a new key look the same: stock["pears"] = 8 updates the pears and stock["kiwis"] = 20 creates the kiwis, which go at the end.
Asking for a missing key with square brackets is an error. get("bananas", 0) is safer: if the key is not there, it returns the default, here 0. And del stock["plums"] removes a key together with its value.
items() gives each key-value pair and, as in the previous lesson, the for unpacks it into fruit and amount. {fruit:<8}{amount:>4} puts them in columns.
keys() gives the keys (list() turns them into a list for printing) and values() the values, which sum() adds up. in checks whether a key exists.
Code · main.py
# A dictionary links keys to values: {key: value}.stock = {"apples": 12, "pears": 5, "plums": 0}print("Apples in stock:", stock["apples"])# Change a value, or add a new key, in the same way.stock["pears"] = 8stock["kiwis"] = 20print(stock)# get() gives a default value when the key does not exist.print("Bananas:", stock.get("bananas", 0))# del removes a key and its value.del stock["plums"]# items() gives each key together with its value.for fruit, amount in stock.items(): print(f"{fruit:<8}{amount:>4}")print("Fruits:", list(stock.keys()))print("Total pieces:", sum(stock.values()))print("Do we sell kiwis?", "kiwis" in stock)Output · python3 main.py
Apples in stock: 12
{'apples': 12, 'pears': 8, 'plums': 0, 'kiwis': 20}
Bananas: 0
apples 12
pears 8
kiwis 20
Fruits: ['apples', 'pears', 'kiwis']
Total pieces: 40
Do we sell kiwis? TrueKey points
- A dictionary goes between
{ }withkey: valuepairs. d[key] = valuechanges or adds.d.get(key, default)does not fail when the key is missing.for k, v in d.items():goes through keys and values.key in dchecks whether the key exists.
Exercise
Add a prices dictionary with the price of each fruit and print the value of the stock: each fruit's amount times its price, and the total at the end.