Python
Cheat sheet · Level 10
Dictionaries
Every command and idea of this level on one page: what to type, what it does, and what you see.
1Labels and values
Dictionaries connect a key to a value.
What to type What it does You see print(prices["tea"])Look up tea · print(prices["cake"])Look up cake 3 7 2Add and change
Put new pairs in.
What to type What it does You see prices["juice"] = 4Add juice · prices["tea"] = 5Change tea {'tea': 5, 'cake': 7, 'juice': 4} False 3Visit every pair
items().
What to type What it does You see for name, price in prices.items():Use items tea: 3 cake: 7 juice: 4 4Only the values, or the keys
values() and keys().
What to type What it does You see print(sum(prices.values()))Use values · print(len(prices.keys()))Use keys 14 3 5Safe look-ups
get() gives a default.
What to type What it does You see print(prices.get("milk", 0))Use get 0 3 6Count with get
Add one, even to a new count.
What to type What it does You see counts[f] = counts.get(f, 0) + 1Use get · for f in basket:Use a loop {'apple': 2, 'pear': 1}