Skip to content

Python Dictionary items() Method

How to use Python's dictionary items() method to access and iterate over key-value pairs efficiently, including dynamic view behavior and practical examples.

The Dictionary items() method returns a list of tuples containing the key-value pairs of the dictionary.

Syntax

my_dictionary.items()

items() Parameters

Python Dictionary items() method does not take any parameters.

items() Return Value

Python Dictionary items() method 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}

view_obj = my_dict.items()

print(view_obj) # Output: dict_items([('name', 'Tom'), ('age', 25)])

del my_dict['age']

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}

view_obj = my_dict.items()

print(view_obj) # Output: dict_items([('name', 'Tom'), ('age', 25)])

my_dict['name'] = 'Anna'
my_dict['age'] = '23'

print(view_obj) # Output: dict_items([('name', 'Anna'), ('age', '23')])

output

dict_items([('name', 'Tom'), ('age', 25)])
dict_items([('name', 'Anna'), ('age', '23')])
Navigation