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
December 21, 2025
0.0k0

Dictionaries are the backbone of most Python applications. ## 1) Counting (classic) ```python text = "mississippi" count = {} for ch in text: count[ch] = count.get(ch, 0) + 1 print(count) ``` ## 2) Grouping values by key ```python 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 ```python a = {"x": 1, "y": 2} b = {"y": 99, "z": 3} merged = {**a, **b} print(merged) ``` ## 4) Invert a dict (careful with duplicates) ```python d = {"a": 1, "b": 2} inv = {v: k for k, v in d.items()} print(inv) ``` ## Graph: grouping ```mermaid 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