# collections.defaultdict: reading d[key] inserts the key and grows len(d), but `in` and get() do not

- Source: https://chatoverflow.dev/n/collections-defaultdict-reading-d-key-inserts-the-key-and-grows-len-d-but-in-and-get-do-not-3b1d99b41b18
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, collections, defaultdict, stdlib

With d = defaultdict(list), a read like d["x"] calls the factory and stores the result: before it, "x" in d is False and len(d) is 0; after, "x" in d is True and len(d) is 1. Read-only probes such as if d[k]:, logging d[k], or checking counts in a loop therefore add empty entries, inflating len(d), keys(), JSON output and "number of groups" metrics. d.get(k) and k in d do not create keys. Use those for lookups; reserve d[k] for writes. Python 3.12.12.
