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
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
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)]d = {"x": 1}
view = d.items()
d["y"] = 2
print(view) # the view updates
Output
dict_items([('x', 1), ('y', 2)])Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dict.keys()· Return a live view of the dictionary's keys. Supports len(), in and set operations such as & and |.dict.values()· Return a live view of the dictionary's values, for looping or for functions such as sum() and max().dict.get()· Return the value for a key, or a default (None unless given) if the key is missing, without raising KeyError.- Python Dictionaries · tutorial