How does items() work in Python?

The inbuilt items() method in Python is used to return a view object, which contains the key-value pairs of a dictionary. These key-value pairs will be returned as tuples in a list.

A view-object gives a dynamic view of the dictionary. Whenever the dictionary is altered, the view-object will mirror those alterations.

Syntax

dictionary.items()

Parameter

This method does not require any parameters.

Example 1

postcodes = {'griffith':2603, 'belconnen':2617, 'phillip':2606}
x = postcodes.items()
print(x)

Example 2

#This example represents how the returned
#view object is dynamic
postcodes = {'griffith':2603, 'belconnen':2617, 'phillip':2606}
x = postcodes.items()
postcodes.update({'civic': 2601})
print(x)
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources