Skip to content

Dictionary with Default Values (Guide)

Zero-dependency Python snippets for dictionaries with default values using the standard library.

11 snippets available in this sub-category.


Simple

Using defaultdict for default values

dict defaultdict default data-structures

defaultdict provides automatic default values

from collections import defaultdict

d = defaultdict(int)
d["a"] += 1
d["b"] += 2
print(dict(d))  # {'a': 1, 'b': 2}

Notes

  • int() gives default 0, list() gives [], set() gives set()
  • No KeyError for missing keys

defaultdict with list (grouping)

dict defaultdict list group data-structures

defaultdict for grouping values

from collections import defaultdict

d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
print(dict(d))  # {'a': [1, 2]}

Notes

  • Each key gets its own independent list

setdefault for default value

dict setdefault default data-structures

setdefault for default value if key missing

d = {}
d.setdefault("a", []).append(1)
print(d)  # {'a': [1]}

Notes

  • setdefault only sets value if key is missing

Advanced Patterns

defaultdict with custom factory

dict defaultdict custom factory data-structures

Custom default value with factory function

from collections import defaultdict


def zero():
    return 0


d = defaultdict(zero)
d["a"] += 5
print(dict(d))  # {'a': 5}

Notes

  • Factory function called for missing keys

defaultdict for counting (Counter)

dict counter count defaultdict data-structures

Counter is a defaultdict(int) for counting

from collections import Counter

lst = ["a", "b", "a"]
c = Counter(lst)
print(dict(c))  # {'a': 2, 'b': 1}

Notes

  • Counter is optimized for counting hashable objects

Nested defaultdict (auto-vivify)

dict defaultdict nested auto data-structures

Auto-vivifying nested defaultdict

from collections import defaultdict


def nested():
    return defaultdict(nested)


d = nested()
d["a"]["b"]["c"] = 42
print(d["a"]["b"]["c"])  # 42

Notes

  • Allows arbitrary depth of nesting without KeyError

Custom dict with missing

dict custom missing default data-structures

Custom dict with missing method

class DefaultDict(dict):
    def __missing__(self, key):
        return 0


d = DefaultDict(a=1)
print(d["a"])  # 1
print(d["b"])  # 0

Notes

  • missing is called for missing keys

Handle missing keys with get()

dict get default data-structures

Use get() for default value if key missing

d = {"a": 1}
print(d.get("b", 0))  # 0

Notes

  • get() does not add the key to the dict

setdefault vs defaultdict

dict setdefault defaultdict compare data-structures

setdefault is explicit, defaultdict is automatic

d = {}
d.setdefault("a", []).append(1)
from collections import defaultdict

dd = defaultdict(list)
dd["a"].append(1)
print(d, dict(dd))  # {'a': [1]} {'a': [1]}

Notes

  • setdefault only sets on missing; defaultdict always provides default

Performance and Edge Cases

Large defaultdicts (performance)

dict defaultdict performance data-structures

defaultdict is fast for large data

import time
from collections import defaultdict

N = 10**6
d = defaultdict(int)
start = time.time()
for i in range(N):
    d[i] += 1
print("Time:", time.time() - start)

Notes

  • defaultdict is efficient for high-volume inserts

Edge cases: missing keys, mutable defaults

dict defaultdict edge-case data-structures

Each key gets its own default value

from collections import defaultdict

d = defaultdict(list)
d["a"].append(1)
print(d["b"])  # []
# All keys get independent lists

Notes

  • Each key gets a new object; no shared mutable default

🔗 Cross Reference

🏷️ Tags

dict, defaultdict, setdefault, default, counter, custom, missing, performance, edge-case, data-structures

📝 Notes

  • defaultdict is best for automatic defaults
  • setdefault is explicit and works with normal dicts
  • Counter is a specialized defaultdict for counting