inspection
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.
key in d / key not in d Parameters
| Parameter | Purpose |
|---|---|
| in | True when the key is present |
| not in | True when the key is absent |
Examples
>>> d = {'a': 1, 'b': 2}
>>> 'a' in d
True
>>> 'z' in d
False Tests key presence, not value
>>> d = {'a': 1}
>>> 1 in d
False
>>> 1 in d.values()
True Use .values() to test for a value (O(n) scan)
>>> d = {'a': 1}
>>> 'x' not in d
True 'not in' is the idiomatic negative form
>>> d = {'a': None}
>>> 'a' in d
True
>>> d.get('a') is None
True Prefer 'in' over d.get(k) is not None when the value might legitimately be None
Gotcha
'in' checks keys only — 'v in d' with a value returns False unless a key equals it. Prefer 'k in d' over 'k in d.keys()' — same result, slightly faster and more idiomatic.
Related methods
dict.get
Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None so this method never raises a KeyError.
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.
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.
← All Python dict methods · String methods · Built-in functions