In this Python tutorial, you will learn what items() method of dictionary dict class does, its syntax, and how to use this method to access all the items in the dictionary, with example programs.

Python Dictionary items

Python Dictionary items() method returns a new view object containing dictionary’s (key, value) pairs. This view object presents dynamic data, which means if any update happens to the dictionary, the view object reflects those changes.

The view object returned by items() is of type dict_items. View objects support iteration and membership checks.

Syntax

The syntax of dict.items() is

dict.items()

items() method returns object of type dict_items.

Examples 2

1 Iterate over dictionary items using dictitems

In this example, we will iterate over the dictionary items using dict.items() iterable.

Python Program

myDictionary = {'a': 58, 'b': 61, 'c': 39}

for item in myDictionary.items():
    print(item)

Program Output

('a', 58)
('b', 61)
('c', 39)

dict.items() returns tuple with data of (key, value) during each iteration. We can access the key and value using index, as shown in the following program.

Python Program

myDictionary = {'a': 58, 'b': 61, 'c': 39}

for item in myDictionary.items():
    print(item[0], '-', item[1])

Program Output

a - 58
b - 61
c - 39

2 Check if an item is present in the dictionary using dictitems

In this example, we will use dict.items() to check if item (key, value) is present in dictionary or not.

Python Program

myDictionary = {'a': 58, 'b': 61, 'c': 39}
item = ('b', 61)

if item in myDictionary.items():
    print('Item present in dictionary.')
else:
    print('Item not present in dictionary.')

Program Output

Item present in dictionary.

As the (key, value) pair is present in the dictionary, the expression item in dict.items() returned True.

Conclusion

In this Python Tutorial, we learned about Python Dictionary method dict.items().