Python 101Free
DATA STRUCTURES

Dictionaries

Key value mappings, the workhorse of Python.

SECTION 01

Lookup as a hash map

A dict maps keys to values via a hash table. When you write d["name"], Python hashes the key, finds the bucket that hash points to, and returns the value stored there. The hashing means lookup is amortized O(1), regardless of how many keys are in the dict.

Keys must be hashable, which in practice means immutable. Strings, numbers, and tuples work as keys. Lists and other dicts do not, because their hash would change if their contents changed.

Dict is the data structure you reach for whenever you need to look something up by name. Counting word frequencies, caching results, configuring options, structuring records returned from an API: all dicts.

python
user = {"name": "Ada", "score": 92}
user["name"]            # 'Ada'

# user[[1, 2]] = "x"    # TypeError: list is unhashable
SECTION 02

Adding, updating, deleting

Assigning to a new key creates the entry. d["b"] = 2. Assigning to an existing key overwrites the value. The same syntax does both, and you cannot tell from the call site which one will happen.

del d["a"] removes a key. d.pop("a", default) removes and returns a value, falling back to a default if the key is absent. Use pop when you want the value too, del when you just want to drop it.

For safe lookup, prefer d.get(key, default) over d[key]. The bracket form raises KeyError if the key is missing, while get returns the default. The bracket form is the right answer when a missing key really is a bug, and get is the right answer everywhere else.

python
d = {"a": 1}
d["b"] = 2              # add
d["a"] = 9              # overwrite
del d["b"]
d.get("missing", 0)     # 0 (no KeyError)
SECTION 03

Iterating items

A dict has three iteration views. d.keys() walks the keys, d.values() walks the values, d.items() walks both as (key, value) pairs. The default iteration of a dict, for k in d:, is equivalent to for k in d.keys().

The most common pattern is for k, v in d.items():, which gives you both at once via tuple unpacking. Use this when you actually need both. Use for k in d: when you only need the keys, since it is shorter and slightly faster.

Iteration order is insertion order in Python 3.7 and later. This is part of the language guarantee, not an implementation detail. You can rely on a dict to give back its keys in the order they were added.

python
prices = {"apple": 3, "pear": 4}
for k, v in prices.items():
    print(k, v)
# apple 3
# pear 4
← PREVIOUS
Tuples
NEXT →
Sets