Python Dictionaries: Keys, Values and Lookups
A dictionary maps keys to values. Instead of asking "what is at position 2?", you ask "what is the price?". Dictionaries are written with braces and colons: {"title": "Paper Cranes", "year": 2016}. Looking up a key is fast no matter how large the dictionary grows, which makes dicts the workhorse for counting, grouping and configuration.
Reading and writing keys
book["title"] returns the value for a key. If the key is missing, square-bracket lookup raises KeyError. When a key may be absent, use book.get("isbn"), which returns None, or book.get("isbn", "n/a") to supply your own default.
Assigning to a key adds it if it is new and replaces the value if it already exists. Keys are unique, so a dict never holds two entries for the same key. Since Python 3.7, dictionaries keep keys in the order they were first inserted; updating a value does not move its key.
Expected output
{'title': 'Paper Cranes', 'year': 2017, 'price': 11.0}
Paper Cranes None n/a
True 3
['title', 'year', 'price']
('title', 'Paper Cranes')
11.0 {'title': 'Paper Cranes', 'year': 2017}
{'pens': 5, 'ink': 2}Useful methods
keys(),values()anditems()return live views of the dictionary. Wrap them inlist()to get a snapshot, or loop over them directly (you will do that in the loops chapter).pop(key)removes a key and returns its value.update(other)copies every key from another dict, overwriting existing ones.setdefault(key, default)returns the value, inserting the default first if the key is missing.key in dchecks keys, not values.
What can be a key?
Keys must be hashable, which in practice means immutable: strings, numbers, and tuples of those are fine. Lists and other dicts cannot be keys. Values have no restriction at all; a value can be a list, another dict, or anything else, which is how nested data such as JSON is represented in Python.
Common mistakes
- Using
d[key]for optional keys and crashing withKeyError. Preferget(). - Expecting
"Paper Cranes" in bookto search values. It checks keys; usein book.values(). - Changing a dict's size while looping over it. Loop over
list(d)if you need to delete keys.
Summary
- Dicts map unique, hashable keys to values.
d[k]raises on a missing key;d.get(k, default)does not.- Assignment adds or replaces;
popremoves;updatemerges. - Insertion order is preserved.
Quiz: Dictionaries