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

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