Dictionary Operations & Advanced Patterns
692 words
3 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Dictionary Operations & Advanced Patterns > **Why read this?** Real programs use dictionaries for grouping, counting, caching, and representing structured data. This topic covers the patterns and tools that make dictionary usage elegant and efficient.

Dictionary Operations & Advanced Patterns
Why read this? Real programs use dictionaries for grouping, counting, caching, and representing structured data. This topic covers the patterns and tools that make dictionary usage elegant and efficient.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Work with nested dictionaries and merge them
- Use
defaultdictandCounterfrom collections module - Use dictionary methods:
setdefault(),update() - Sort dictionaries by keys or values
- Use dictionaries for memoization (caching)
📋 Prerequisites
📖 Core Content
20.1 Nested Dictionaries
python# runnable users = { "alice": {"age": 25, "city": "NYC", "scores": [85, 92]}, "bob": {"age": 30, "city": "LA", "scores": [70, 88]}, "charlie": {"age": 22, "city": "Chicago", "scores": [95, 91]} } print(users["alice"]["city"]) # NYC print(users["bob"]["scores"][0]) # 70 # Iterate nested dict for username, info in users.items(): avg_score = sum(info["scores"]) / len(info["scores"]) print(f"{username}: {avg_score:.1f}%")
20.2 Dictionary Merge and Update
python# runnable d1 = {"a": 1, "b": 2} d2 = {"c": 3, "d": 4} # Merge (Python 3.9+) merged = d1 | d2 print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Update (modifies in place) d1.update(d2) print(d1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Both methods handle overlapping keys (last wins)
20.3 setdefault() — Get or Set Default
python# runnable # Without setdefault data = {} words = ["apple", "banana", "apple", "cherry", "banana"] for word in words: if word not in data: data[word] = 0 data[word] += 1 # With setdefault (elegant) data2 = {} for word in words: data2.setdefault(word, 0) data2[word] += 1
20.4 defaultdict — Automatic Default Values
python# runnable from collections import defaultdict # Default value is int (0) freq = defaultdict(int) for word in ["apple", "banana", "apple", "cherry"]: freq[word] += 1 print(dict(freq)) # {'apple': 2, 'banana': 1, 'cherry': 1} # Default value is list groups = defaultdict(list) for name in ["Alice", "Bob", "Charlie", "Alice", "Bob"]: groups[name].append(len(name)) print(dict(groups))
20.5 Counter — Counting Made Easy
python# runnable from collections import Counter words = ["apple", "banana", "apple", "cherry", "banana", "apple"] counter = Counter(words) print(counter) # Counter({'apple': 3, 'banana': 2, 'cherry': 1}) print(counter.most_common(2)) # [('apple', 3), ('banana', 2)] print(counter["grape"]) # 0 (no error for missing keys!)
20.6 Sorting Dictionaries
python# runnable grades = {"Alice": 85, "Bob": 72, "Charlie": 90, "Diana": 78} # Sort by key for name in sorted(grades): print(f"{name}: {grades[name]}") # Sort by value (ascending) for name in sorted(grades, key=grades.get): print(f"{name}: {grades[name]}") # Sort by value (descending) for name in sorted(grades, key=grades.get, reverse=True): print(f"{name}: {grades[name]}")
20.7 Worked Example: Group by First Letter
python# runnable from collections import defaultdict names = ["Alice", "Bob", "Charlie", "David", "Eve", "Anna", "Ben"] groups = defaultdict(list) for name in names: groups[name[0]].append(name) print(dict(groups)) # {'A': ['Alice', 'Anna'], 'B': ['Bob', 'Ben'], 'C': ['Charlie'], 'D': ['David'], 'E': ['Eve']}
⚠️ Common Pitfalls
Pitfall 1: Forgetting defaultdict Factory
The mistake:
dd = defaultdict() — missing the factory function. Fix: dd = defaultdict(int) for counting, defaultdict(list) for grouping.Pitfall 2: Nested Key Access Without Checking
The mistake:
users["alice"]["scores"] — works IF "alice" exists. But users["unknown"]["scores"] crashes. Fix: Use .get() for safe chaining, or check if "alice" in users: first.Pitfall 3: Mutating Default Values
The mistake: A
defaultdict's default value is shared if using defaultdict(lambda: []) incorrectly. Fix: Use defaultdict(list) correctly — each new key gets its OWN list.📝 Practice Questions
Q1: What does Counter("mississippi").most_common(3) return?Answer:[('i', 4), ('s', 4), ('p', 2)](i and s tied at 4 each) Q2: Write code to invert a dictionary (swap keys and values).Answer:pythonoriginal = {"a": 1, "b": 2, "c": 3} inverted = {v: k for k, v in original.items()}Q3-10: Additional advanced dict questions.(Following pattern.)
🔗 Cross-References
- Next Topic: Functions
- Previous Topic: Dictionaries
- Reference: Python for Everybody, Chapter 9 (Sections 9.3-9.4)
- Video: L59: More on dictionaries Join Discord Previous19. DictionariesNext21. Functions