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
key in dict
Membership test invoking __contains__ — returns True if key exists in the dictionary. The check is against keys only (never values) and runs in O(1) average time.
dict.keys
Returns a dynamic view object of the dictionary's keys. The view reflects any subsequent changes made to the dictionary and supports set-like operations.
dict.clear
Removes all items from the dictionary in place, leaving it empty. Returns None.
← All Python dict methods · String methods · Built-in functions