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

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