iteration
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.
d.items() Parameters
| Parameter | Purpose |
|---|---|
| (no parameters) | items() takes no arguments |
| returns | dict_items view of 2-tuples |
Examples
>>> d = {'a': 1, 'b': 2}
>>> list(d.items())
[('a', 1), ('b', 2)] Get a list of (key, value) pairs
>>> for k, v in {'a': 1, 'b': 2}.items():
... print(k, v)
a 1
b 2 Standard iteration pattern with tuple unpacking
>>> {'a': 1, 'b': 2}.items() & {('a', 1)}
{('a', 1)} Set-like intersection works when values are hashable
>>> swapped = {v: k for k, v in {'a': 1, 'b': 2}.items()}
>>> swapped
{1: 'a', 2: 'b'} Invert a dict with a comprehension over items
Gotcha
Set operations on items() raise TypeError if any value is unhashable (e.g. lists). Never mutate the dict during iteration — it raises RuntimeError.
Related methods
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.
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.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
← All Python dict methods · String methods · Built-in functions