all Python 3Dictionaries (dict)construct
Access d[key]
access
d[key] returns the value for a key or raises KeyError if absent. To avoid the error on a missing key, use dict.get() with a default.
Syntax
d[key]
Reading and writing through square brackets are not symmetric: d[key] = 1 happily creates a missing key, while reading that same key raises KeyError. Key lookup is O(1) on average, so an in check before access costs almost nothing; but when the key is normally present, it is cheaper to read and catch KeyError instead. Note too that d.get(key) returns None both for a missing key and for a key whose value is None — only in, or your own sentinel as the default, tells those apart.
Examples
d = {'a': 1, 'b': 2}
print(d['a']) # → 1
print('z' in d) # → False (проверка перед d[key])
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy