Lesson 8 of 52Collections
Dictionaries
Map keys to values with dicts, use get, setdefault, Counter and defaultdict, and understand why lookups are O(1).
If lists are Python's workhorse, dictionaries are its skeleton. JSON from an API becomes a dict. A user record is a dict. Counting words, grouping orders by customer, caching results: all dicts. Even Python itself uses dicts internally to store your variables. In interviews, "use a hash map" is the answer to a huge share of problems, and in Python that means a dict.
Keys and values
A dictionary (dict) maps keys to values. You look things up by key instead of by position.
Press Run (⌘ Enter) to see what happens.The rules are short:
- Keys are unique. Assigning to an existing key replaces its value.
- Keys must be hashable (strings, numbers, tuples; not lists). Values can be anything.
inchecks keys, not values.- Since Python 3.7, dicts keep insertion order: items come back in the order you added them.
Reading safely: get and setdefault
Looking up a missing key with square brackets raises KeyError. Often a missing key is normal, so use .get(key, default), which returns the default instead (or None if you give no default).
Press Run (⌘ Enter) to see what happens.setdefault(key, default) is a cousin: if the key is missing, it inserts the default and returns it; if present, it returns the existing value. It is handy for grouping:
Press Run (⌘ Enter) to see what happens.What does this print?
prices = {"tea": 3, "cake": 0}
print(prices.get("cake", 5), prices.get("coffee", 5))Looping over a dict
Looping over a dict gives you its keys. Use .values() for values, and .items() for (key, value) pairs, which you unpack right in the for.
Press Run (⌘ Enter) to see what happens.Do not add or remove keys while looping over a dict; Python raises RuntimeError: dictionary changed size during iteration. Loop over list(d) (a copy of the keys) if you must delete as you go.
d = {"a": 1, "b": 2}, what is 2 in d?Views: keys(), values() and items() are live
keys(), values() and items() do not copy anything. They return views: thin windows onto the dict that always show its current contents. Create a view, change the dict, and the view reflects the change without being asked again.
Key views go further. Because keys are unique and hashable, a key view behaves like a set, so you can use &, |, - and ^ on it directly. Item views are set-like too, as long as the values are hashable. Value views are not set-like, because values can repeat and need not be hashable.
Press Run (⌘ Enter) to see what happens.That set behaviour is the cleanest way to compare two records at work. "Which fields did the client send that we do not know about?" is payload.keys() - ALLOWED_FIELDS: one line, no loop.
The rule about iteration is precise. Adding or removing keys while you loop changes the size of the table and raises RuntimeError: dictionary changed size during iteration. Replacing the value of a key that already exists is allowed, because the table layout does not move. When you need to delete as you go, iterate over list(d), or build a new dict with a comprehension, which is usually clearer anyway: stock = {k: v for k, v in stock.items() if v}.
ks = d.keys(), then d['new'] = 1. What does 'new' in ks give?How a dict finds things so fast
A dict is a hash table. When you store a key, Python computes the key's hash (a number derived from its value) and uses it to pick a bucket, a slot in an internal array. To look the key up later, it hashes again and jumps straight to that bucket. No scanning.
scores["ada"] = 91. The hash of "ada" picks bucket 6, so the pair goes there.
That is why lookups, inserts and deletes are O(1) on average. "On average" because with many collisions the work grows, and in a pathological worst case it is O(n). Python keeps the table less than about two-thirds full and grows it as needed, so in practice that worst case does not happen.
It also explains the hashable rule. If a list could be a key and you appended to it, its hash would change and Python would look in the wrong bucket forever. So mutable types are banned as keys.
What can be a key
"Hashable" is less a property of a type than a promise. An object can be a key when two things hold:
hash(x)never changes whilexis in the dict.- If
a == b, thenhash(a) == hash(b).
The dict relies on both. It uses the hash to find the right slot and then == to confirm it found the right key. Break rule 1 and the key is stranded in a slot Python will never look in again. Break rule 2 and two equal keys can live side by side. Strings, numbers, None, tuples of hashable things and frozenset all keep the promise. Lists, dicts and sets do not, so they are refused.
Rule 2 has a surprise built into it. 1 == 1.0 == True is true in Python, so they must hash the same, and a dict treats them as one key. The first key you inserted stays; later assignments only replace the value.
Tuples make excellent composite keys. A sparse grid, a cache keyed on several arguments, or "orders by (customer, month)" all fall out naturally, with no string gluing like f"{row}-{col}" that breaks the moment a value contains a dash.
Press Run (⌘ Enter) to see what happens.The last two lines show the failure you will meet in real code. Point computes __hash__ from mutable fields, so after p.x = 99 its hash points to a different slot and p in seen is False. A fresh Point(1, 2) finds the old slot but fails the == check against the mutated object. The entry is still in the dict, and nothing can reach it. The fix is to make key objects immutable: a frozen dataclass, a NamedTuple, or a plain tuple. Dunder Methods covers the __eq__ and __hash__ contract in full, and Dataclasses shows frozen=True.
What does this print?
d = {1: "int", 1.0: "float", True: "bool"}
print(d, len(d))Counting and grouping: Counter and defaultdict
Two tools from the collections module remove most dict boilerplate. You will use them constantly.
Counter counts things. Give it any iterable and it returns a dict-like object of item to count, with a handy most_common() method.
defaultdict is a dict that creates a default value for missing keys automatically, so you never need get or setdefault for grouping.
Press Run (⌘ Enter) to see what happens.Match each task to the tool that fits best.
Merging and building dicts
A few more operations you will see in real code:
Press Run (⌘ Enter) to see what happens.What does this print?
a = {"x": 1, "y": 2}
b = {"y": 20, "z": 30}
merged = a | b
print(merged["y"], len(merged))|, |=, ** and update: which one
There are four ways to merge, and they differ in small ways that come up in code review:
a | bbuilds a new dict and leaves both inputs alone. Both sides must be dicts;a | [("k", 1)]is aTypeError.a |= bupdatesain place, exactly likea.update(b). It is more forgiving: the right side can be any mapping or any iterable of pairs.{**a, **b, "debug": True}also builds a new dict, and lets you mix in literal keys and more than two sources. It was the idiom before 3.9 and you will read it everywhere.a.update(b, debug=True)mutatesaand also takes keyword arguments.
In every form the right-most value wins and the key keeps its original position. Merges are also shallow: if a value is a nested dict, the merged dict holds the same nested object, so changing merged["db"]["port"] changes the defaults too. Deep-merging config is a job for a small recursive function, not for |.
Press Run (⌘ Enter) to see what happens.Order is guaranteed, and when OrderedDict still matters
Since Python 3.7 the language guarantees that a dict remembers insertion order. Updating the value of an existing key does not move it; deleting a key and inserting it again puts it at the end. That guarantee is why JSON round-trips keep their field order, and why dict.fromkeys(items) is the idiomatic way to remove duplicates while keeping the first occurrence of each.
collections.OrderedDict predates the guarantee, and most code that uses it today could use a plain dict. It still has three real differences:
- Equality is order-sensitive. Two
OrderedDicts with the same items in a different order are not equal. Two plain dicts are. move_to_end(key, last=True)moves a key to either end in O(1).popitem(last=False)removes from the front in O(1). A plain dict'spopitem()only removes the last item.
Those last two are exactly what a least-recently-used (LRU) cache needs: move a key to the end when you use it, and evict from the front when you are full. "Build an LRU cache" is a common interview task, and OrderedDict is the expected Python answer. In production you would usually reach for functools.lru_cache, covered in functools, itertools and operator.
Press Run (⌘ Enter) to see what happens.After put("home") and put("about"). The cache is full. The front is the oldest entry.
Layered and read-only mappings: ChainMap and MappingProxyType
Two more standard library tools solve problems you meet in configuration code.
collections.ChainMap looks up a key in several dicts in order and returns the first hit, without copying any of them. That is exactly how settings usually work: command-line flags override environment variables, which override defaults. Reads search every layer. Writes and deletes only touch the first layer, so the defaults are never modified by accident. Because nothing is copied, a change to any underlying dict shows up immediately.
types.MappingProxyType wraps a dict in a read-only view. Code that receives the proxy can read but cannot assign, so it is a cheap way to expose module-level constants or internal state without handing out a mutable dict. It is a view, not a copy: whoever holds the original dict can still change it. Python itself uses this for a class's __dict__.
Press Run (⌘ Enter) to see what happens.If you want a mapping that is truly immutable and hashable, so that it can itself be a dict key or a set member, Python 3.15 adds the built-in frozendict. It is covered in What Changed in Python 3.11 to 3.15. It does not run in the browser here, which uses 3.14.
What does this print?
from collections import ChainMap
base = {"a": 1, "b": 2}
over = {"b": 20}
cm = ChainMap(over, base)
cm["a"] = 100
print(base["a"], cm["a"], len(cm))Word count
Write word_count(text) that returns a dict mapping each word to how many times it appears. Treat words case-insensitively (store them in lowercase). Words are separated by whitespace.
word_count("the cat and the hat") → {"the": 2, "cat": 1, "and": 1, "hat": 1}
word_count("Go go GO") → {"go": 3}text.lower().split() gives you a list of lowercase words.
Invert a dict
Write invert(d) that returns a new dict with keys and values swapped. If two keys share a value, the key that comes last wins.
invert({"apple": "red", "sky": "blue"}) → {"red": "apple", "blue": "sky"}
invert({"a": "x", "b": "x"}) → {"x": "b"}All values are hashable.
- dict
- A mapping from unique, hashable keys to values. Keeps insertion order (3.7+).
- hash table
- Stores items in buckets chosen by the key's hash, giving O(1) average lookups.
- collision
- Two keys landing in the same bucket. Handled by probing and comparing keys with
==. - dict.get
d.get(key, default)returns the value, or the default if the key is missing. NoKeyError.- Counter
- A dict subclass from
collectionsthat counts items; hasmost_common(n). - defaultdict
- A dict that creates a default value (like
[]or0) for missing keys on first access. - dict view
- The live, copy-free object returned by
keys(),values()oritems(). Key views support set operations. - OrderedDict
- A dict subclass with order-sensitive equality,
move_to_endandpopitem(last=False). The classic LRU building block. - ChainMap
- Looks keys up through several mappings in order; writes go to the first. Used for layered config.
- MappingProxyType
- A read-only view of a dict. Readers cannot change it, but the owner of the dict still can.