iteration
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.
d.keys() Parameters
| Parameter | Purpose |
|---|---|
| (no parameters) | keys() takes no arguments |
| returns | dict_keys view — iterable, len-able, supports & | - ^ |
Examples
>>> d = {'a': 1, 'b': 2}
>>> list(d.keys())
['a', 'b'] Materialize with list() when you need an indexable sequence
>>> d = {'a': 1, 'b': 2}
>>> ks = d.keys()
>>> d['c'] = 3
>>> list(ks)
['a', 'b', 'c'] View is dynamic — reflects later mutations
>>> {'a': 1, 'b': 2}.keys() & {'b', 'c'}
{'b'} Set-like intersection with any iterable
>>> for k in {'a': 1, 'b': 2}:
... print(k)
a
b Iterating a dict directly is the same as iterating its keys
Gotcha
Mutating the dict while iterating its keys view raises RuntimeError. Iteration order is insertion order (guaranteed since Python 3.7).
Related methods
dict.values
Returns a dynamic view object of the dictionary's values. Unlike keys(), the values view is not set-like because values may be non-hashable or duplicated.
dict.items
Returns a dynamic view of (key, value) tuple pairs. The view is set-like when all values are hashable and reflects subsequent changes to the dictionary.
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.
← All Python dict methods · String methods · Built-in functions