Dictionaries

Python · Essentials · 10 min

Dicts are the most important data structure in Python — objects, JSON and kwargs are all dicts underneath.

A dict maps keys to values: ages = {"ana": 31, "ben": 27}. Lookup by key, ages["ana"], is O(1) on average because dicts are hash tables. Keys must be hashable — immutable built-ins like str, int and tuples of those; lists and dicts can't be keys. Since Python 3.7 dicts preserve insertion order.

Reading a missing key with d[key] raises KeyError. Choose the right tool:

  • d.get(key) returns None (or d.get(key, default)) if absent
  • key in d tests for a key (not a value)
  • d.setdefault(key, []).append(x) inserts a default the first time

Writing is plain assignment, d[key] = value, which inserts or overwrites. del d[key] and d.pop(key, default) remove. d.update(other) merges in another mapping, and d1 | d2 (3.9+) returns a merged new dict, with the right side winning on conflicts.

Iterating a dict yields its keys. Use the view methods for more:

  • for k, v in d.items(): — both, the most common
  • d.keys(), d.values() — live views that reflect later changes

Counting and grouping are bread-and-butter dict jobs: counts[w] = counts.get(w, 0) + 1. (The collections module's Counter and defaultdict make these even shorter; you'll meet them later.)

Don't add or delete keys while iterating over a dict — Python raises RuntimeError. Iterate over list(d) if you need to.

Example

ages = {"ana": 31, "ben": 27}
ages["cy"] = 40                    # insert
ages["ana"] += 1                   # update
print(ages)          # {'ana': 32, 'ben': 27, 'cy': 40}

print(ages.get("dan"))             # None
print(ages.get("dan", 0))          # 0
print("ben" in ages)               # True

for name, age in ages.items():
    print(f"{name}: {age}")

counts = {}
for word in "the cat and the hat".split():
    counts[word] = counts.get(word, 0) + 1
print(counts)        # {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}

defaults = {"theme": "light", "size": 12}
print(defaults | {"size": 14})   # {'theme': 'light', 'size': 14}

Remember

  • Keys must be hashable; lookup is O(1) on average
  • Use .get() or in when a key may be missing
  • Iterate with .items(); dicts keep insertion order

Watch out for

  • Using d[key] on keys that might not exist and getting KeyError.

Check yourself

  1. Which of these can be a dict key?
  2. What does `for x in {"a": 1, "b": 2}:` iterate over?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/tutorial/datastructures.html#dictionaries