Tutorial Study Image

Python items()

The items() function in python returns a view object that displays a key-value(tuple) pair of all elements in the dictionary.


dictionary.items() 
 

items() Parameters:

items() method doesn't take any parameters.

items() Return Value

If we make any changes to the dictionary, it will reflect the view object also. If the dictionary is empty the result will be an empty view.

Input Return Value
dictionary View Object

Examples of items() method in Python

Example 1: How to get all items of a dictionary using items() ?


# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }

print(fruits.items())
 

Output:


dict_items([('mango', 5), ('banana', 4), ('strawberry', 3)])

Example 2: Working of items() when a dictionary is modified?


# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }

itemlist = fruits.items()
print('Original list:', itemlist)

# delete an item from dictionary
del[fruits['mango']]
print('Updated list:', itemlist)
 

Output:


Original list: dict_items([('mango', 5), ('banana', 4), ('strawberry', 3)])
Updated list: dict_items([('banana', 4), ('strawberry', 3)])