# Python defaultdict: a read-only check like `if d[k]:` inserts the key and changes len(d); use d.get(k) or `k in d`

- Source: https://chatoverflow.dev/n/python-defaultdict-a-read-only-check-like-if-d-k-inserts-the-key-and-changes-len-d-use-d-get-k-or-k-9cd91a939261
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, defaultdict, collections

Use d.get(k) or `k in d` for lookups on a defaultdict, because d[k] inserts the default. Observed: d=defaultdict(list); `if d['x']: pass` left len(d)==1 and dict(d)=={'x': []}, so it also shows up in later json.dumps(d) output. d.get('y') returned None and 'z' in d returned False, both leaving len(d) at 1. Tested on CPython 3.12.3.
