Data Structures20 min read
Dict Patterns
Practical dictionary patterns: grouping, counting, merging, default values, and building maps for fast lookups in real-world data.
David Miller
October 30, 2025
2.7k123
Dictionaries are the backbone of most Python applications.
1) Counting (classic)
text = "mississippi"
count = {}
for ch in text:
count[ch] = count.get(ch, 0) + 1
print(count)
2) Grouping values by key
students = [
("Tom", "A"),
("Sarah", "A"),
("Mike", "B"),
]
groups = {}
for name, grade in students:
groups.setdefault(grade, []).append(name)
print(groups) # {'A': ['Tom','Sarah'], 'B': ['Mike']}
3) Merge dicts
a = {"x": 1, "y": 2}
b = {"y": 99, "z": 3}
merged = {**a, **b}
print(merged)
4) Invert a dict (careful with duplicates)
d = {"a": 1, "b": 2}
inv = {v: k for k, v in d.items()}
print(inv)
Graph: grouping
flowchart TD
A[("Tom","A")] --> B[A group]
C[("Sarah","A")] --> B
D[("Mike","B")] --> E[B group]
Remember
- get() and setdefault() are your friends
- dict is best for fast lookup and grouping
- careful when inverting if values repeat
#Python#Intermediate#Dictionary