all Python 3Dictionaries (dict)term
in / not in for a dict
search
in checks for a KEY in the dictionary, in O(1). To test the values, use in d.values().
Syntax
key in d | key not in d
Membership hashes the key, so an unhashable object raises TypeError: unhashable type rather than returning False — [] in d is the classic case. It never tests pairs; for that you need ('a', 1) in d.items(). And if k in d: d[k] does two lookups in a row — d.get(k, default) or try/except KeyError is usually cleaner.
Examples
d = {'a': 1, 'b': 2}
print('a' in d)
# → True
print('c' in d)
# → False
print('c' not in d)
# → True
print(1 in d)
# → False (1 — не ключ!)
print(1 in d.values())
# → True (проверка значений)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy