MOD-12 · Sequence #12 · Python Collections

Python Dictionaries

Python dictionaries (dict) are associative arrays mapping unique keys to values. Since Python 3.7, dictionary keys maintain insertion order. They provide average O(1) key lookups, deletions, and insertions, and support dictionary comprehensions.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(car.get("color", "Red"))  # 'Red'

Core Principles & Mental Models

1. Dictionary Lookups and .get()

Avoiding KeyError with Defaults

  • Accessing a nonexistent key via bracket syntax `d[key]` raises a KeyError.
  • The `.get(key, default)` method returns `None` (or your chosen fallback) if the key is not found, preventing crashes.
  • The `setdefault(key, default)` method returns the value if present, or inserts and returns default if absent.
counts = {"apple": 5}
# print(counts["banana"]) -> Raises KeyError!
print("Banana count:", counts.get("banana", 0))
💡 Key Takeaway: Use `.get()` when a key might be missing and you have a sensible default.

2. Iterating Dictionaries and Comprehensions

.keys(), .values(), .items()

  • Iterating directly over a dict iterates over its keys: `for k in d:`.
  • Use `.items()` to iterate over key-value pairs simultaneously: `for k, v in d.items():`.
  • Dict comprehensions allow transforming mappings: `{k: v**2 for k, v in d.items()}`.
grades = {"Alice": 85, "Bob": 92, "Charlie": 78}
honors = {name: score for name, score in grades.items() if score >= 90}
print("Honors list:", honors)
💡 Key Takeaway: `.items()` returns a dynamic view of key-value pairs in insertion order.

Interactive Walkthrough Examples

Word Frequency Counter (Basic)

Building a word frequency map using .get() with fallback.

text = "python is fun and python is powerful"
words = text.split()
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
for word, count in freq.items():
    print(f"'{word}': {count}")

Explanation: freq.get(w, 0) + 1 increments the existing count or starts at 0 + 1 for new keys.

Common Misconceptions & Exam Traps

Common Pitfall: Modifying Dictionary Keys During Iteration (RuntimeError)

Modifying the internal hash table while iterating invalidates the iterator.

Buggy Code
d = {"a": 1, "b": 2, "c": 3}
for k in d:
    if d[k] % 2 == 0:
        del d[k]  # RuntimeError: dictionary changed size during iteration!
Correct Solution
d = {"a": 1, "b": 2, "c": 3}
for k in list(d.keys()):  # Iterate over an independent list snapshot
    if d[k] % 2 == 0:
        del d[k]
print("Cleaned:", d)

Exam Trap Note: Exams frequently check if you know to iterate over `list(d.keys())` when deleting items in a loop.

Conceptual Knowledge Self-Check Quiz

Q1: What is returned by `d.get("missing", 42)` if the key "missing" is not in dictionary `d`?

  1. KeyError exception
  2. None
  3. 42
  4. False

`.get(key, default)` returns the second argument (42 in this case) when the key does not exist.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Use collections.defaultdict for counting or grouping items into lists.
  • ✅ Remember that dictionary keys must be hashable (tuples are allowed; lists are not).

All 26 Curriculum Modules