From defaultdict(int) to nested lambdas, graph adjacency lists, and LeetCode problems.
Every pattern you need — predict outputs, spot gotchas, and write real solutions.
defaultdict(factory) auto-creates a default value when you access a missing key.
The factory is a callable — called with no arguments to produce the default.
This eliminates the KeyError and replaces clunky if key not in d: d[key] = ... boilerplate.
int → counters. list → grouping. set → unique grouping.
lambda → any custom default.
d = {}
d["x"] += 1 # KeyError!
# Must write:
if "x" not in d:
d["x"] = 0
d["x"] += 1
from collections import defaultdict
d = defaultdict(int)
d["x"] += 1 # auto-init to 0
# Clean, readable, fast
int → 0
list → []
set → set()
str → ""
float → 0.0
lambda: 42 → 42
lambda: {} → {}
lambda: defaultdict(int) → nested dd
# When d[key] is missing:
# Python calls d.__missing__(key)
# Which calls: default_factory()
# And stores the result at d[key]
# You can override __missing__
# yourself on a plain dict subclass
from collections import defaultdict d = defaultdict(int) words = ["apple", "banana", "apple", "cherry", "banana", "apple"] for w in words: d[w] += 1 print(d["apple"]) print(d["banana"]) print(d["mango"]) # key does not exist print(len(d))
defaultdict(int) calls int() — which returns 0 — when a missing key is accessed.
So d["mango"] silently creates the key with value 0 and returns it.
That's why len(d) is 4 — "mango" was added to the dict the moment you accessed it.
This is the most common gotcha: reading a missing key creates it.
from collections import defaultdict d = defaultdict(int) print(d["x"])
What is printed, and what happens to d?
defaultdict calls int()
to produce 0, stores it at d["x"], then returns it.
The dict is now {"x": 0}. This is different from dict.get("x", 0)
which returns 0 without creating the key. Use .get() when you don't want side effects.
from collections import defaultdict d = defaultdict(int) d["a"] = 5 print(d["a"]) print(d["b"]) print("b" in d) print(d.get("c")) print("c" in d)
d["b"] triggers __missing__ → creates "b": 0 → "b" in d is now True.
But d.get("c") does NOT trigger __missing__ — it returns None without creating the key.
So "c" in d stays False.
d.get(key) when you want to check a value without creating the key.
defaultdict(int) with the frequency of each character.
Then return the character with the highest frequency. If tied, return the lexicographically smallest.
from collections import defaultdict def char_freq(s: str): # Count every character in one pass freq = defaultdict(int) for ch in s: freq[ch] += 1 # Two-key sort: highest count first, then lex smallest on tie best = sorted(freq, key=lambda ch: (-freq[ch], ch))[0] return freq, best
(-freq[ch], ch) — negative count puts higher counts first;
the character string itself breaks ties lexicographically.
This is the same pattern as LeetCode 692 Top K Frequent Words.
from collections import defaultdict words = ["apple", "avocado", "banana", "blueberry", "cherry"] groups = defaultdict(list) for w in words: groups[w[0]].append(w) print(groups["a"]) print(groups["b"]) print(groups["z"])
defaultdict(list) calls list() — returns [] — for any missing key.
Accessing groups["z"] creates an empty list. No KeyError, no pre-check needed.
This replaces the pattern: if key not in d: d[key] = [] / d[key].append(...).
# Option A d1 = {} d1.setdefault("x", []).append(1) d1.setdefault("x", []).append(2) # Option B from collections import defaultdict d2 = defaultdict(list) d2["x"].append(1) d2["x"].append(2)
What is d1["x"] and d2["x"]?
[1, 2]. setdefault returns the existing value if the key exists,
so the second call returns the same list (already [1]) and appends 2 to it.
defaultdict(list) does the same thing more cleanly — no need to pass the default on every access.
defaultdict when you always use the same default type.
setdefault when the default might vary per call.
defaultdict(list).
from collections import defaultdict def invert(d: dict) -> dict: # Group original keys by their value inv = defaultdict(list) for k, v in d.items(): inv[v].append(k) return dict(inv) # convert back to plain dict for clean output
.items(), swap key/value, append to the new list.
Without defaultdict, you'd write if v not in inv: inv[v] = [] every time.
Converting back with dict(inv) is good practice — callers get a plain dict, not a defaultdict.
from collections import defaultdict import re def build_index(lines): index = defaultdict(list) for line_num, line in enumerate(lines): # Extract only word characters, lowercase words = re.findall(r'\b[a-z]+\b', line.lower()) for word in words: index[word].append(line_num) return dict(index)
defaultdict(list) lets you append line numbers without checking if the word was seen before.
re.findall(r'\b[a-z]+\b', ...) cleanly strips punctuation.
from collections import defaultdict d = defaultdict(set) pairs = [("a", 1), ("b", 2), ("a", 1), ("a", 3), ("b", 2)] for k, v in pairs: d[k].add(v) print(sorted(d["a"])) print(sorted(d["b"])) print(d["c"])
list collects duplicates; set deduplicates automatically.
The pair ("a", 1) appears twice but d["a"] holds {1, 3} — only unique values.
d["c"] creates an empty set(), shown as set() (not {} — that's an empty dict!).
(u, v), build an adjacency list using defaultdict(set).
Then return all neighbours of a given node, sorted.
from collections import defaultdict def build_graph(edges): graph = defaultdict(set) for u, v in edges: graph[u].add(v) # undirected — add both directions graph[v].add(u) return graph def neighbours(graph, node): return sorted(graph[node]) # sorted for deterministic output
(1,2)
appears twice in input, the graph is still correct — no duplicate neighbours.
This is the standard way to build graphs in Python interview problems.
from collections import defaultdict d = defaultdict(lambda: "unknown") d["name"] = "Alice" print(d["name"]) print(d["age"]) print(d["city"])
"unknown".
Any missing key gets this default. Explicit keys override it normally.
This replaces dict.get(key, "unknown") — useful when you're accessing many keys
and want a consistent fallback without repeating the default everywhere.
from collections import defaultdict # lambda: [] creates a NEW list for each missing key d = defaultdict(lambda: []) d["a"].append(1) d["b"].append(2) print(d["a"]) print(d["b"]) print(d["a"] is d["b"])
d["a"] and d["b"] are two different list objects — is returns False.
def f(x=[]): — there, the same list is shared. With defaultdict(lambda: []), each call creates a new list. Safe.
defaultdict(lambda: []) is equivalent to defaultdict(list). Prefer list.
from collections import defaultdict # Count down from 10 for each new key d = defaultdict(lambda: 10) d["x"] -= 3 d["y"] -= 7 d["x"] -= 2 print(d["x"]) print(d["y"]) print(d["z"])
d["x"] starts at 10 (lambda), then -= 3 makes it 7, then -= 2 makes it 5.
d["y"] starts at 10, -= 7 → 3.
d["z"] is accessed for the first time → lambda returns 10. Nothing else changes it.
lambda: N — is useful for problems where new counters start at a non-zero baseline.
defaultdict(lambda: 100).
Apply a list of (player, delta) events. Return final scores for all players seen.
from collections import defaultdict def track_scores(events): # Each new player starts at 100 automatically scores = defaultdict(lambda: 100) for player, delta in events: scores[player] += delta return dict(scores)
defaultdict, you'd write: if player not in scores: scores[player] = 100
before every update. The lambda removes that boilerplate entirely.
scores[player] += delta reads the current value (100 if new), adds delta, stores back.
from collections import defaultdict # Two-level: outer key → inner key → count d = defaultdict(lambda: defaultdict(int)) d["alice"]["python"] += 3 d["alice"]["java"] += 1 d["bob"]["python"] += 5 print(d["alice"]["python"]) print(d["alice"]["go"]) # not set yet print(d["bob"]["python"]) print(list(d.keys()))
defaultdict uses lambda: defaultdict(int)
so each new outer key gets a fresh inner defaultdict(int).
d["alice"]["go"] accesses a missing inner key → inner defaultdict returns 0.
defaultdict(defaultdict(int))?
That would call defaultdict(int) once and share the same inner dict for all outer keys — a shared-state bug!
Always use lambda: defaultdict(int) for nesting, so each key gets its own fresh inner dict.
from collections import defaultdict # BUG: defaultdict(int) is evaluated ONCE here inner = defaultdict(int) d = defaultdict(inner) # passing an instance, not a factory! d["alice"]["python"] += 3 d["bob"]["python"] += 5 print(d["alice"]["python"])
What does this print — and why is the code wrong?
defaultdict(inner) passes the same defaultdict(int) instance as the factory.
When Python calls inner() it calls the defaultdict as a function.
A defaultdict is callable and calling it with no args returns 0 (calls its own factory). This means d["alice"] and d["bob"] both get the
same inner dict object!
So d["alice"]["python"] += 3 and d["bob"]["python"] += 5 both write to the same key, totaling 8.
lambda: defaultdict(int) — the lambda is called fresh each time, creating a new inner dict.
(user, action) events, count how many times each user performed each action.
Use a nested defaultdict. Return the count for a specific (user, action) pair.
from collections import defaultdict def build_action_map(events): # outer: user → inner: action → count action_map = defaultdict(lambda: defaultdict(int)) for user, action in events: action_map[user][action] += 1 return action_map def count_actions(events, user, action): action_map = build_action_map(events) # .get() avoids creating the key if user/action not seen return action_map.get(user, {}).get(action, 0)
action_map[user][action] += 1 — two bracket accesses, both safe.
For querying, use .get() chains to avoid creating keys just from reading.
This two-level structure (user → action → count) appears constantly in analytics and log processing problems.
from collections import defaultdict d = defaultdict(int) keys_to_check = ["a", "b", "c"] for k in keys_to_check: if d[k] == 0: # accessing d[k] creates the key! pass print(list(d.keys()))
d[k]
triggered __missing__ and created them with value 0.
d.get(k, 0) == 0 to check without creating the key.
Or use k in d to check existence. Only use d[k] when you intend to create the key.
from collections import defaultdict d = defaultdict(None) d["a"] = 1 print(d["b"])
default_factory is None,
defaultdict behaves exactly like a regular dict — it raises KeyError for missing keys.
Setting it to None disables the auto-creation behaviour.
from collections import defaultdict d = defaultdict(list) d["a"].append(1) d["b"].append(2) plain = dict(d) plain["c"] # access missing key on plain dict
dict(dd) creates a plain dict. All keys and values are copied.
But the auto-creation behaviour is gone — plain["c"] raises KeyError.
dict(dd) from functions so callers get predictable plain dicts.
Keep the defaultdict internal. This prevents callers from accidentally creating keys via reads.
from collections import defaultdict def my_factory(key="default"): return key.upper() d = defaultdict(my_factory) print(d["x"])
my_factory() uses its default arg key="default",
so it returns "default".upper() = "DEFAULT".
defaultdict directly.
You'd need to subclass dict and override __missing__(self, key).
class SmartDict(dict): def __missing__(self, key): # Called automatically when key not found value = key.upper() self[key] = value # store so it's not recomputed return value d = SmartDict() print(d["hello"]) print(d["world"]) print(list(d.keys()))
defaultdict uses internally.
By subclassing dict and overriding it, you can create factories that know the missing key.
This is the answer to Q21's limitation — when you need the key to compute the default.
defaultdict is just a dict subclass that implements __missing__ to call default_factory().
That's the whole magic — nothing more.
from collections import defaultdict def groupAnagrams(strs): # Key insight: anagrams share the same sorted character tuple groups = defaultdict(list) for s in strs: key = tuple(sorted(s)) # "eat" → ('a','e','t') groups[key].append(s) return list(groups.values())
defaultdict(list) auto-creates the group when a new anagram signature is seen.
Without it, you'd need: if key not in groups: groups[key] = [].
defaultdict(int) to count, then bucket sort by frequency.
from collections import defaultdict def topKFrequent(nums, k): # Step 1: count frequencies freq = defaultdict(int) for n in nums: freq[n] += 1 # Step 2: bucket sort — index = frequency, value = list of nums buckets = defaultdict(list) for num, count in freq.items(): buckets[count].append(num) # Step 3: collect top-k from highest freq bucket down result = [] for count in range(len(nums), 0, -1): result.extend(buckets[count]) if len(result) >= k: break return result[:k]
defaultdict(int) for counting,
defaultdict(list) for bucketing by frequency.
Bucket sort gives O(n) time — better than heap-based O(n log k) approaches.
buckets[count] safely returns [] for any count with no numbers — no need to check if count exists.
{frequency: count_of_words_with_that_freq}.
Use two defaultdict(int)s chained together.
from collections import defaultdict def freq_of_freq(words): # Step 1: word → its frequency word_freq = defaultdict(int) for w in words: word_freq[w] += 1 # Step 2: frequency → how many words have it fof = defaultdict(int) for count in word_freq.values(): fof[count] += 1 return dict(fof)
defaultdict as the keys of the second.
This is a very common two-pass pattern: first count something, then count the counts.
Appears in problems like "Find the Celebrity", "Find All Anagrams", and database aggregation.
defaultdict(int) is that both passes look identical —
just d[key] += 1 — regardless of what kind of key you're counting.
defaultdict(int) → counters, frequencies, prefix sumsdefaultdict(list) → grouping, indexing, adjacency listsdefaultdict(set) → unique grouping, deduplication, graph edgesdefaultdict(lambda: X) → any custom constant defaultdefaultdict(lambda: defaultdict(int)) → two-level grouping.get() to peek without side effectslambda: defaultdict(...) — never pass an instance directlydict(dd) from functions — callers get clean, predictable plain dicts