Python dictionary items() method
Return the (key, value) pairs, for looping over both.
Syntax
dict.items()
The usual way to loop over a dictionary: for key, value in d.items():. The result is a live view: it reflects later changes.
Parameters
None.
Return value
a view of (key, value) pairs
Example
Code
ages = {"Sita": 27, "Leo": 31} for name, age in ages.items(): print(f"{name} is {age}") print(list(ages.items())) print(sorted(ages.items(), key=lambda kv: kv[1], reverse=True))
Output
Sita is 27
Leo is 31
[('Sita', 27), ('Leo', 31)]
[('Leo', 31), ('Sita', 27)]
Good to know.
for k, v in d: fails: looping over a dictionary gives only the keys.Related
Learn it step by step in the free lesson Dictionaries & Sets, with exercises that check your answers.