HomeGuidesPythonPython Dictionaries Explained — Methods, Iteration & Common Traps
🐍 Python

Python Dictionaries: Methods, Iteration, and Exam Traps

Dictionaries are tested heavily in Python exams. Here's what you need to know — from key access to comprehensions to common gotchas.

Examifyr·2026·5 min read

Creating and accessing dictionaries

Dictionaries store key-value pairs. Keys must be immutable (strings, numbers, tuples). Accessing a missing key raises a KeyError.

person = {"name": "Alice", "age": 30}

print(person["name"])           # "Alice"
print(person.get("age"))        # 30
print(person.get("email"))      # None  — no KeyError
print(person.get("email", ""))  # ""   — custom default
Note: Always use .get() when the key might not exist. Using [] on a missing key raises KeyError.

Adding, updating, and deleting keys

Assignment adds or updates. del removes a key. pop() removes and returns the value.

d = {"a": 1, "b": 2}

d["c"] = 3          # add
d["a"] = 99         # update
del d["b"]          # delete (KeyError if missing)
val = d.pop("c")    # remove and return value
val = d.pop("x", 0) # safe pop with default

Iterating over dictionaries

You can iterate over keys, values, or key-value pairs. `.items()` is the most useful in exams.

scores = {"Alice": 90, "Bob": 78, "Carol": 85}

for key in scores:                # iterates keys
    print(key)

for value in scores.values():     # iterates values
    print(value)

for name, score in scores.items():  # key-value pairs
    print(f"{name}: {score}")

Dictionary comprehensions

Like list comprehensions, but produces a dictionary.

squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Filter: only scores above 80
top = {k: v for k, v in scores.items() if v > 80}
# {"Alice": 90, "Carol": 85}

Merging dictionaries

Python 3.9+ supports the | operator. For older Python, use .update() or **unpacking.

a = {"x": 1, "y": 2}
b = {"y": 99, "z": 3}

# Python 3.9+
merged = a | b          # {"x": 1, "y": 99, "z": 3}

# Works in all Python 3
merged = {**a, **b}     # same result
# b's values win on duplicate keys
Note: When keys overlap, the rightmost dictionary wins. This is frequently tested.

Exam tip

Know the difference between dict["key"] (raises KeyError) and dict.get("key") (returns None). Also know what .items(), .keys(), and .values() return — they return view objects, not lists.

🎯

Think you're ready? Prove it.

Take the free Python readiness test. Get a score, topic breakdown, and your exact weak areas.

Take the free Python test →

Free · No sign-up · Instant results

← Previous
Python Lists — Slicing, Methods & List Comprehensions Explained
Next →
Python Loops Explained — for, while, enumerate, zip & break/continue
← All Python guides