Returns a list of key-value pairs in a dictionary
Usage
The items()
method returns a list of tuples containing the key:value pairs of the dictionary. The first item in each tuple is the key, and the second item is its associated value.
Syntax
dictionary.items()
Examples
# Print all items from the dictionary
D = {'name': 'Bob', 'age': 25}
L = D.items()
print(L)
# Prints dict_items([('age', 25), ('name', 'Bob')])
items()
method is generally used to iterate through both keys and values of a dictionary. The return value is the tuples of (key, value)
.
# Iterate through both keys and values of a dictionary
D = {'name': 'Bob', 'age': 25}
for x in D.items():
print(x)
# Prints ('age', 25)
# Prints ('name', 'Bob')
items() Returns View Object
The object returned by items()
is a view object. It provides a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
D = {'name': 'Bob', 'age': 25}
# Assign dict items to L
L = D.items()
# modify dict D
D['name'] = 'xx'
# L reflects changes done to dict D
print(L)
# Prints dict_items([('age', 25), ('name', 'xx')])