Phase 2 · Data StructuresModule 10~34 min read

Dictionaries

Fast key-value mapping — the most important data structure in Python.

What you'll learn

The dictionary is arguably the most important data structure in Python. It stores key → value pairs with lightning-fast lookup — like a real dictionary where you look up a word (the key) to find its definition (the value). You'll use it everywhere.

By the end you'll be able to:

  • Create dictionaries and look up values safely
  • Add, update, and delete key-value pairs
  • Iterate keys, values, and items
  • Build dictionaries concisely with dict comprehensions
  • Use Counter and defaultdict from collections

Creating & accessing

A dictionary uses curly braces with key: value pairs. Keys must be unique and immutable (strings, numbers, tuples). You look up a value by its key:

Keys map to values
"Sara"──▶25
"Omar"──▶30
"Aisha"──▶22

A dictionary maps unique keys to values. Looking up a key is near-instant, no matter how large the dictionary grows.

dicts.py
ages = {"Sara": 25, "Omar": 30}

print(ages["Sara"])            # 25
print(ages.get("Aisha", 0))    # 0   (a default if the key is missing)
print("Omar" in ages)          # True
print(len(ages))               # 2

Use .get() for safety

Accessing a missing key with ages["missing"] raises a KeyError. .get(key, default) returns your default instead of crashing — much safer when a key might not exist.

Modifying dictionaries

Dictionaries are mutable. Assigning to a key adds it (or updates it if it exists); del removes it; and .update() merges another dictionary in:

modify.py
ages = {"Sara": 25}

ages["Omar"] = 30      # add a new key
ages["Sara"] = 26      # update an existing key
ages.update({"Aisha": 22, "Sam": 40})
del ages["Omar"]       # delete a key

print(ages)

Note

Since Python 3.7, dictionaries remember insertion order — iterating gives you keys back in the order you added them. You can also merge with the | operator: combined = a | b.

Iterating over dictionaries

Looping over a dictionary gives you its keys by default. To get keys and values together, use .items() — one of the most common patterns in all of Python:

iterate.py
prices = {"apple": 1.5, "banana": 0.5}

for key in prices:                    # iterating gives the KEYS
    print(key)

for fruit, price in prices.items():   # .items() gives key AND value
    print(f"{fruit}: {price}")
MethodReturns
.keys()all the keys
.values()all the values
.items()(key, value) pairs
.get(k, default)value for k, or default
.setdefault(k, d)get k, inserting d if missing
.pop(k)remove k and return its value

Dict comprehensions

Just like list comprehensions (coming in Module 12), you can build a dictionary in one readable line with a dict comprehension: {key: value for item in iterable}:

comprehension.py
squares = {n: n * n for n in range(1, 6)}
print(squares)

# invert a dictionary (swap keys and values)
prices = {"apple": 1.5, "banana": 0.5}
by_price = {price: fruit for fruit, price in prices.items()}
print(by_price)

Counter & defaultdict

The collections module offers specialised dictionaries that save you writing common code by hand. Counter tallies how often things appear — perfect for counting words, votes, or events:

counter.py
from collections import Counter

votes = ["yes", "no", "yes", "yes", "no"]
counts = Counter(votes)

print(counts)                  # Counter({'yes': 3, 'no': 2})
print(counts["yes"])           # 3
print(counts.most_common(1))   # [('yes', 3)]

Note

defaultdict is another gem: it auto-creates a default value for missing keys (like an empty list), so you can write groups[key].append(x) without first checking whether key exists. Both are covered more in Module 29.

Recap & quick check

Key takeaways

  • Dictionaries map unique, immutable keys to values with near-instant lookup.
  • Use .get(key, default) to avoid a KeyError when a key might be missing.
  • Assigning to a key adds or updates it; del removes; .update() merges. Insertion order is preserved.
  • Iterate with .items() to get keys and values together.
  • Build them with dict comprehensions; Counter tallies frequencies and defaultdict handles missing keys.

Quick check

1. What does a dictionary store?

2. How do you safely get a value that might be missing?

3. Which method gives you keys and values together while iterating?

4. What must dictionary keys be?

5. What does collections.Counter do?

Excellent — you've mastered Python's most-used structure. Next up: Module 11 — Sets.