inspection

len(dict)

Built-in that invokes __len__ to return the number of key-value pairs in the dictionary. Runs in O(1) — the count is maintained internally, not recomputed.

len(d)

Parameters

Parameter Purpose
d Any dict (or subclass implementing __len__)
returns Non-negative int: count of keys

Examples

>>> len({'a': 1, 'b': 2, 'c': 3})
3

Counts key-value pairs (== count of unique keys)

>>> len({})
0

Empty dict has length 0

>>> d = {'a': 1, 'b': 2}
>>> if d:
...     print('non-empty')
non-empty

Empty dicts are falsy — use 'if d' instead of 'if len(d) > 0'

len({'a': 1, 'a': 2})

`1` — duplicate literal keys collapse to a single entry (last value wins). len() counts the deduplicated key count, not the source literal count.

Gotcha

Prefer truthiness ('if d') over 'if len(d)' — it's faster and more Pythonic. len() only counts top-level keys, not nested entries.

Related methods

← All Python dict methods · String methods · Built-in functions