Python Dictionary items() Function
The Dictionary 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
.
The items()
method is particularly useful when you need to iterate over the key-value pairs of a dictionary, especially in for loops where you can unpack the key and value directly in the loop variable assignment.
Syntax
my_dictionary.items()
items() Parameters
Python Dictionary items()
function does not take any parameters.
items() Return Value
Python Dictionary items()
function returns a view object that displays a list of a given dictionary's (key, value) tuple pair.
Examples
Example 1: Get all items of a dictionary
For example, let's print all the items form a dictionary:
my_dict = {'name': 'Tom', 'age': 25}
print(my_dict.items()) # Output: dict_items([('name', 'Tom'), ('age', 25)])
output
dict_items([('name', 'Tom'), ('age', 25)])
Example 2: Iterate through a dictionary using items()
The items()
method is generally used to iterate through both keys and values of a dictionary. Remember that the return value of items()
is a list of tuples as (key, value).
For example, let's iterate through both keys and values of a dictionary:
my_dict = {'name': 'Tom', 'age': 25}
for x in my_dict.items():
print(x)
output
('name', 'Tom')
('age', 25)
Example 3: items() returns a View Object (Reflecting Changes to the Dictionary)
The object returned by items()
is a view object.
It provides a dynamic view on the dictionary’s entries: this means that when the dictionary changes, the view reflects these changes.
For example, when an item is deleted from the dictionary, the view object automatically updates to reflect the change:
my_dict = {'name': 'Tom', 'age': 25}
# Assign dict items to view_obj
view_obj = my_dict.items()
# print view_obj
print(view_obj) # Output: dict_items([('name', 'Tom'), ('age', 25)])
# Delete an item from the dictionary
del my_dict['age']
# print view_obj to see reflected changes
print(view_obj) # Output: dict_items([('name', 'Tom')])
output
dict_items([('name', 'Tom'), ('age', 25)])
dict_items([('name', 'Tom')])
The same happens when an item is modified in the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
# Assign dict items to view_obj
view_obj = my_dict.items()
# print view_obj
print(view_obj) # Output: dict_items([('name', 'Tom'), ('age', 25)])
# modify dictionary my_dict
my_dict['name'] = 'Anna'
my_dict['age'] = '23'
# view_obj reflects changes done to dictionary my_dict
print(view_obj) # Output: dict_items([('name', 'Anna'), ('age', '23')])
output
dict_items([('name', 'Tom'), ('age', 25)])
dict_items([('name', 'Anna'), ('age', '23')])