Skip to content

Lesson 8 of 52Collections

Dictionaries

Map keys to values with dicts, use get, setdefault, Counter and defaultdict, and understand why lookups are O(1).

19 min read0/7 questions

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.

Python
user = { "name": "Ada", "age": 29, "languages": ["python", "sql"],} print(user["name"])user["age"] = 30 # update an existing keyuser["city"] = "London" # add a new keydel user["languages"] # remove a keyprint(user)print(len(user), "age" in user)
Output
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.
  • in checks 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).

Python
stock = {"apple": 5, "pear": 0} print(stock.get("apple", 0))print(stock.get("mango", 0))print(stock.get("mango")) try: stock["mango"]except KeyError as err: print("KeyError:", err)
Output
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:

Python
orders = [("ada", "book"), ("sam", "pen"), ("ada", "lamp")]by_customer = {}for customer, item in orders: by_customer.setdefault(customer, []).append(item)print(by_customer)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

prices = {"tea": 3, "cake": 0}
print(prices.get("cake", 5), prices.get("coffee", 5))
Need a nudge? Hints walk you through it.

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.

Python
scores = {"ada": 91, "sam": 78, "priya": 85} for name in scores: print(name) print(sum(scores.values())) for name, score in scores.items(): print(f"{name}: {score}")
Output
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.

Quick check
With d = {"a": 1, "b": 2}, what is 2 in d?
Need a nudge? A hint rules out a wrong answer.

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.

Python
stock = {"apple": 5, "pear": 0, "plum": 3}keys = stock.keys()print(keys)stock["fig"] = 7print(keys) # the same view, now showing fig online = {"apple": 5, "kiwi": 2}print(stock.keys() & online.keys()) # in bothprint(sorted(stock.keys() - online.keys())) # only in stockprint(stock.items() & {("apple", 5)}) # matching pairs try: for name in stock: if stock[name] == 0: del stock[name]except RuntimeError as err: print("RuntimeError:", err) for name in list(stock): # snapshot the keys first if stock[name] == 0: del stock[name]print(stock) for name in stock: # changing values is fine stock[name] *= 2print(stock)
Output
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}.

Quick check
You run ks = d.keys(), then d['new'] = 1. What does 'new' in ks give?
Need a nudge? A hint rules out a wrong answer.

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.

Storing scores in a hash table

puthash("ada") % 8 = 6

  1. 0empty
  2. 1empty
  3. 2empty
  4. 3empty
  5. 4empty
  6. 5empty
  7. 6"ada":91
  8. 7empty

scores["ada"] = 91. The hash of "ada" picks bucket 6, so the pair goes there.

1/6

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:

  1. hash(x) never changes while x is in the dict.
  2. If a == b, then hash(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.

Python
grid = {}grid[(0, 0)] = "start"grid[(2, 1)] = "wall"print(grid[(2, 1)], grid.get((5, 5), "empty")) row, col = 1, 1for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]: print((row + dr, col + dc), grid.get((row + dr, col + dc), ".")) try: {["a", "b"]: 1}except TypeError as err: print("TypeError:", err) class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __hash__(self): return hash((self.x, self.y)) p = Point(1, 2)seen = {p: "home"}p.x = 99 # mutate a key: the promise is brokenprint(Point(1, 2) in seen, p in seen) # lost both ways
Output
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.

Predict the outputPython

What does this print?

d = {1: "int", 1.0: "float", True: "bool"}
print(d, len(d))
Need a nudge? Hints walk you through it.

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.

Python
from collections import Counter, defaultdict words = "the cat and the hat and the bat".split()counts = Counter(words)print(counts["the"], counts["dog"]) # missing keys count as 0print(counts.most_common(2)) by_length = defaultdict(list)for w in words: by_length[len(w)].append(w)print(dict(by_length))
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

Match each task to the tool that fits best.

Choose an item, then its match on the other side.

Merging and building dicts

A few more operations you will see in real code:

Python
defaults = {"theme": "light", "font": 14}user_prefs = {"theme": "dark"} settings = defaults | user_prefs # merge (3.9+): right side winsprint(settings) settings.update({"font": 16}) # merge into an existing dictprint(settings) pairs = [("a", 1), ("b", 2)]print(dict(pairs)) # build from (key, value) pairsprint(dict(zip(["x", "y"], [10, 20]))) # or from two lists
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

a = {"x": 1, "y": 2}
b = {"y": 20, "z": 30}
merged = a | b
print(merged["y"], len(merged))
Need a nudge? Hints walk you through it.

|, |=, ** and update: which one

There are four ways to merge, and they differ in small ways that come up in code review:

  • a | b builds a new dict and leaves both inputs alone. Both sides must be dicts; a | [("k", 1)] is a TypeError.
  • a |= b updates a in place, exactly like a.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) mutates a and 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 |.

Python
defaults = {"theme": "light", "db": {"port": 5432}}user = {"theme": "dark"} merged = {**defaults, **user, "debug": True}print(merged) merged["db"]["port"] = 6543 # shallow: the nested dict is sharedprint(defaults["db"]) prefs = {"a": 1}prefs |= [("b", 2)] # |= accepts pairsprint(prefs)try: prefs | [("c", 3)]except TypeError as err: print("TypeError:", err)
Output
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's popitem() 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.

Python
from collections import OrderedDict print(dict.fromkeys(["b", "a", "b", "c", "a"]).keys()) # de-duplicate, keep order a = {"x": 1, "y": 2}b = {"y": 2, "x": 1}print(a == b, OrderedDict(a) == OrderedDict(b)) class LRU: def __init__(self, capacity): self.capacity = capacity self.data = OrderedDict() def get(self, key): if key not in self.data: return None self.data.move_to_end(key) # mark as most recently used return self.data[key] def put(self, key, value): self.data[key] = value self.data.move_to_end(key) if len(self.data) > self.capacity: self.data.popitem(last=False) # evict the least recently used cache = LRU(2)cache.put("home", "<home>")cache.put("about", "<about>")cache.get("home")cache.put("blog", "<blog>") # evicts about, not homeprint(list(cache.data))
Output
Press Run (⌘ Enter) to see what happens.
An LRU cache of size 2 (front is least recently used)
home
0
about
1
capacity = 2

After put("home") and put("about"). The cache is full. The front is the oldest entry.

1/4

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__.

Python
from collections import ChainMapfrom types import MappingProxyType defaults = {"region": "eu-west-2", "retries": 3, "debug": False}env = {"retries": 5}cli = {"debug": True} config = ChainMap(cli, env, defaults)print(config["region"], config["retries"], config["debug"]) config["timeout"] = 30 # writes go to the first map onlyprint(cli)print(defaults)print(dict(config)) _settings = {"currency": "GBP", "vat": 0.2}SETTINGS = MappingProxyType(_settings)try: SETTINGS["vat"] = 0except TypeError as err: print("TypeError:", err)_settings["vat"] = 0.25 # the owner can still change itprint(SETTINGS["vat"])
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.
ChallengeEasy

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.

Python
def word_count(text: str) -> dict[str, int]: # Start with an empty dict and count each word. pass
ChallengeEasy

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.

Python
def invert(d: dict) -> dict: # Walk the key/value pairs and store them the other way round. pass
Key terms
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. No KeyError.
Counter
A dict subclass from collections that counts items; has most_common(n).
defaultdict
A dict that creates a default value (like [] or 0) for missing keys on first access.
dict view
The live, copy-free object returned by keys(), values() or items(). Key views support set operations.
OrderedDict
A dict subclass with order-sensitive equality, move_to_end and popitem(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.