dict.items()
Returns a live view of a dictionary's key-value pairs as tuples, so you can loop over the key and its value together.
dict.items()items() gives you every entry of a dictionary as a pair (key, value). Its main use is in a for loop loop: for name, age in people.items(): hands you both parts on each round.
It is also the way to sort a dictionary by its values, to filter it, or to turn it into a list of pairs.
The result is a view that follows the dictionary as it changes. You may change the value of an existing key while looping, but adding or deleting keys during the loop raises a RuntimeError.
Return value
A dict_items view of (key, value) tuples.
Examples
1Loop over keys and values
prices = {"coffee": 2.5, "tea": 2.0, "cake": 3.75}
for item, price in prices.items():
print(f"{item}: ${price:.2f}")coffee: $2.50 tea: $2.00 cake: $3.75
2What the pairs look like
point = {"x": 3, "y": 7}
print(point.items())
print(list(point.items()))dict_items([('x', 3), ('y', 7)])
[('x', 3), ('y', 7)]3Sort a dictionary by value
scores = {"Lena": 82, "Omar": 95, "Yuki": 77}
ranking = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
for place, (name, score) in enumerate(ranking, start=1):
print(place, name, score)1 Omar 95 2 Lena 82 3 Yuki 77
4Filter a dictionary
stock = {"pens": 40, "ink": 0, "paper": 12, "glue": 0}
in_stock = {k: v for k, v in stock.items() if v > 0}
print(in_stock){'pens': 40, 'paper': 12}5Swap keys and values
codes = {"GR": "Greece", "PT": "Portugal"}
by_name = {country: code for code, country in codes.items()}
print(by_name["Portugal"])PT
Common mistakes
Looping over the dictionary and expecting pairs
for k, v in d: loops over the keys only, then tries to unpack each key into two names. Add .items().
ages = {"Ana": 30, "Ben": 25}
for name in ages:
print(name)
for name, age in ages.items():
print(name, age)Ana Ben Ana 30 Ben 25
Adding or deleting keys during the loop
The dictionary may not change size while you loop over its view. Loop over a copy: for k, v in list(d.items()):.
cart = {"apple": 0, "pear": 2}
for k, v in list(cart.items()):
if v == 0:
del cart[k]
print(cart){'pear': 2}Questions people ask
How do I iterate over a dictionary in Python?
for key, value in d.items():. Use for key in d: for keys only and for value in d.values(): for values only.
How do I sort a dictionary by value?
dict(sorted(d.items(), key=lambda kv: kv[1])) gives a new dictionary in value order.
How do I get the first key-value pair?
next(iter(d.items())) gives the first pair without building a whole list.