items() method in Python Dictionary

Published: July 06, 2022

items() method in Python Dictionary

In this article, we would cover items() method in Python Dictionary. The items() method returns with a view object. Or, we can say it returns with a list of items in dictionary in form of (key, value) pairs. The view will reflect any changes made to the dictionary (more in Example II).

Following is the syntax for items() -

dictionary_name.items()

We discuss more about it with relevant examples next.

items() method in Python Dictionary

Let's say we have a dictionary, x -

x = {"name":"abc", "age":24, "address":"xyz, qwerty"}

Example I. For view of dictionary items, use the following code -

y = x.items()

Then, use print() method -

print(y)

It would return with -

dict_items([('name', 'abc'), ('age', 24), ('address', 'xyz, qwerty')])

Example II. Here, we will see what happens if we make changes to an item in the dictionary? Will it change view object as well?

y = x.items()
print("Without any changes: ", y)

We store the outcome of x.items() in variable y. Thereafter, use print() method to view the outcome.

As already discussed in the first paragraph of the article - the view will reflect any changes made to the dictionary. Therefore, at this point if we just make changes to an item in the dictionary x, it should be there when we use print(y). Notice here that, we won't use the code y = x.items() again.

x['name'] = "abc_replaced"
print("Changes made to dictionary: ", y)

This would result in -

Without any changes: dict_items([('name', 'abc'), ('age', 24), ('address', 'xyz, qwerty')])
Changes made to dictionary: dict_items([('name', 'abc_replaced'), ('age', 24), ('address', 'xyz, qwerty')])

Clearly, when we made changes to the dictionary item and didn't even use the code y = x.items() the second time. Still the view object shows us with the update.

In conclusion, we have discussed the items() method in Python dictionary.