Skip to main content

items()

The items() method in Python is a dictionary method that returns a view object that displays a list of tuple pairs (key, value) in the dictionary. This method is used to access all key-value pairs in the dictionary in the form of tuples.

Parameter Values

This function does not accept any parameters.

Return Values

The items() method returns a view object with tuples (key, value) from the dictionary.

How to Use items() in Python

Example 1:

The items() method in Python returns a view object that displays a list of a dictionary's key-value tuple pairs.

dict = {'a': 1, 'b': 2, 'c': 3}
print(list(dict.items()))
# Output: [('a', 1), ('b', 2), ('c', 3)]
Example 2:

This method allows you to iterate over the key-value pairs in a dictionary using a for loop.

dict = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}
for key, value in dict.items():
    print(f'The color of {key} is {value}')
Example 3:

You can also use the items() method with list comprehension to manipulate the data in the dictionary and create a new list of formatted strings.

dict = {'John': 25, 'Alice': 30, 'Bob': 28}
formatted_list = [f'{name} is {age} years old' for name, age in dict.items()]
print(formatted_list)
# Output: ['John is 25 years old', 'Alice is 30 years old', 'Bob is 28 years old']