Python dict.items() Method

Summary: The dictionary data structure has many useful methods, one of these methods is the dict.items() method. To be able to iterate and show the dictionary elements, the Python dictionary items() method does this functionality. The dict.items() method shows the elements taken up by a dictionary as a list of key-value tuples.

Definition: The dict.items() method outputs a list of (key, value) tuple pairs of a dictionary.

Syntax of dict.items()

Method Declaration:

dict.items()

Parameters: The dict.items() method does not input any parameters

Return Value: The dict.items() method outputs a view object type that shows a list of (key, value) tuple pairs of a dictionary in the form:

[(key_1, value), (key_2, value), ..., (key_nth, value)]

Grocery Items example to show the results when a dictionaries state changes

# Declare a dictionary of grocery items
grocery_items = {'bread': '$5.00',
                 'melon': '$2.99',
                 'eggs': '$6.00'}


# Print grocery_items as tuples
print(grocery_items.items())


# Show if dictionary changes propagate to items() view
current_groceries = grocery_items.items()
print('original groceries: ', current_groceries)
del[grocery_items['melon']]
print('updated groceries: ', current_groceries)

Output:

dict_items([('bread', '$5.00'), ('melon', '$2.99'), ('eggs', '$6.00')])
original groceries:  dict_items([('bread', '$5.00'), ('melon', '$2.99'), ('eggs', '$6.00')])
updated groceries:  dict_items([('bread', '$5.00'), ('eggs', '$6.00')])

The results show that the current_groceries dictionary refers to the original grocery_items dictionary. Thus, removing items from the original grocery_items will also affect the results of the current_groceries dictionary being called.