dict.items()
Python · Dictionaries
Theory
.items() returns a view of all key-value pairs of a dictionary, each pair as a (key, value) tuple, in insertion order. Combined with tuple unpacking in a for loop, for k, v in employee.items():, it gives you both the key and its value on every iteration, which is the most common way to walk through a dictionary. For employee = {'name': 'Asha', 'salary': 65000}, the loop prints name Asha and then salary 65000.
Like keys() and values(), items() is a live view, not a copy, so it is cheap even for big dicts. It also powers handy patterns: dict comprehensions such as {k: v for k, v in d.items() if v > 0} to filter, sorted(d.items(), key=lambda kv: kv[1]) to sort by value, and dict(pairs) to build a dict back from pairs. One rule: do not add or delete keys while looping over items(); Python raises RuntimeError: dictionary changed size during iteration. Loop over list(d.items()) if you must modify.
Why we use it
Most dictionary work needs the key and the value together: printing a report, filtering by value, transforming every entry. items() gives both in one step, without a second lookup like d[k] inside the loop.
When to use it
Use items() whenever a loop needs both key and value. Use values() when you only need the values and plain for k in d when you only need keys. Iterate over a list(d.items()) copy if the loop changes the dict's size.
How it works
- for k, v in employee.items():
- Ask the view for the next (key, value) pair
- Is there another pair? Yes: Unpack it into k and v. No: Leave the loop.
- Run the loop body with k and v, e.g. print(k, v)
- Output: name Asha, then salary 65000
Syntax
dict.items()Example
employee = {'name': 'Asha', 'salary': 65000}
for k, v in employee.items():
print(k, v)Key points
- The most common way to iterate a dictionary's contents
- Each pair comes back as a (key, value) tuple
- Returns a live view, not a copy
- Sort by value: sorted(d.items(), key=lambda kv: kv[1])
- Changing the dict's size inside the loop raises RuntimeError