Python 3 reference · Dictionary Methods

Python Dictionary items() Method

Return a live view of the dictionary's (key, value) pairs, used to loop over keys and values together.

Python 3 Since 3.0

Syntax

dict.items()

Return value

A dict_items view that reflects later changes.

Examples

Loop over keys and valuesTry it yourself
prices = {"tea": 2.5, "cake": 4.0}
for name, price in prices.items():
    print(f"{name}: {price:.2f}")

Output

tea: 2.50
cake: 4.00
Sort by valueTry it yourself
scores = {"Ada": 91, "Linus": 88, "Grace": 95}
print(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))

Output

[('Grace', 95), ('Ada', 91), ('Linus', 88)]
Views are liveTry it yourself
d = {"x": 1}
view = d.items()
d["y"] = 2
print(view)  # the view updates

Output

dict_items([('x', 1), ('y', 2)])

Version history

VersionChange
Python 3.0Added