Dictionaries: Looking Up by Name
A list finds things by position: the third item, the last item. But most real questions are asked by name. How much did I spend on food? What is Anna's phone number? A dictionary stores values under keys, so you ask with the key and get the value straight back, without searching.
Think of a filing cabinet with labelled drawers. You do not count drawers from the top; you read the labels and open the one marked "food". A dictionary is that cabinet: each key is a label, and each value is what is filed under it.
Keys and Values
A dictionary is written in curly braces. Inside, each entry is a key, a colon, and its value, and entries are separated by commas. Keys are usually strings. To look something up, put the key in square brackets after the dictionary's name, the way you put an index after a list.
>>> phones = {"Anna": "555-0101", "Omar": "555-0142"}
>>> phones["Anna"]
'555-0101'
Adding and Replacing
Assigning to a key adds an entry if the key is new, and replaces the value if it already exists. A dictionary can never hold the same key twice: the new value simply takes the old one's place. len counts the entries.
>>> phones["Lena"] = "555-0177"
>>> phones["Anna"] = "555-0199"
>>> phones
{'Anna': '555-0199', 'Omar': '555-0142', 'Lena': '555-0177'}
>>> len(phones)
3
Dictionaries keep their entries in the order they were first added. Replacing Anna's number did not move her to the end; adding Lena put her there.
Totalling Spending by Category
Here is the job dictionaries do best. The list below holds a month of payments, each as a pair: a category and an amount. The program walks the list and keeps a running total per category in a dictionary. The first time a category appears, it is not yet a key, so the program starts it at zero; after that, it adds to it. Food, with two payments, comes to 58.50.
from decimal import Decimal payments = [ ["food", Decimal("54.30")], ["transport", Decimal("45.00")], ["food", Decimal("4.20")], ["home", Decimal("61.75")], ["fun", Decimal("12.50")], ] totals = {} for payment in payments: category = payment[0] amount = payment[1] if category not in totals: totals[category] = Decimal("0") totals[category] = totals[category] + amount print(totals) print(f"Food: {totals['food']}")
{'food': Decimal('58.50'), 'transport': Decimal('45.00'), 'home': Decimal('61.75'), 'fun': Decimal('12.50')}
Food: 58.50
Two new small things appear here. not in asks whether a key is absent from the dictionary, and it reads like English. And inside the f-string on the last line, the key is written in single quotes, because the f-string itself uses double quotes. Python 3.12 and later would also accept double quotes there, but mixing the two kinds is clearer to read and works on every version.
Keys Are Unique
Because each key appears only once, a dictionary is the natural home for anything that should have exactly one value per name: one total per category, one number per person, one price per product. When you do need several values under one key, store a list as the value.
- "Dictionaries sort their keys." They keep the order in which keys were first added. Sort explicitly when you need another order.
- "A key can hold two values." Assigning to an existing key replaces its value. Store a list under the key if you need several.
- "Keys must be strings." Strings are the usual choice, but numbers and other unchangeable values work as keys too.
- "Group by a name and total" is one of the most common jobs done with data, and a dictionary does it in a few lines.
- Data from the internet arrives as dictionaries, so this is also the skill for reading it in Chapter 10.
Knowledge Check
What does phones["Anna"] do?
- Gives the value stored under the key Anna
- Gives the position of Anna in the dictionary
- Adds Anna to the dictionary with no value
- Counts how many times Anna appears as a key
After d = {"a": 1} and then d["a"] = 5, what is in d?
- Both 1 and 5, stored under the key a
- An error, because the key a already exists
- One entry, a with the value 5
- Two separate entries that are both called a
In the category program, why does it check if category not in totals first?
- To skip every payment in a category it has seen
- Because dictionaries only accept keys that are sorted
- To stop the program from printing the same category twice
- A new category has no total yet, so it must start at zero
In what order does a dictionary keep its entries?
- Alphabetical order of the keys
- Smallest value first, largest last
- The order in which the keys were first added
- No order at all, different on every run
You got correct