Python read items from dict:

The items() method returns a new view of the dictionary items as a list of tuples referred as “dict_items” containing keys and values. As this is a view of the dictionary, all the updates made to the dictionary is also visible in the view.

Method signature

The signature for the items() method is as shown below. Here, d refers to the dictionary and v is a view over the dictionary.

v=d.items()

Method parameters and return type

  • The items() method takes no parameters.
  • However, it returns a view object that displays keys and values of a dictionary as a list of tuples.

Python Dictionary items Examples:

Example 1:

Let us take a dictionary with numbers assigned to colour names in this example. Here, we will extract the key-value pair as a list. Also, we can see the list is named dict_items.

#Initializing 
color={1:"Red",2:"Blue",3:"Green"}
# Using items method
v1=color.items()
#Printing 
print("View has ",v1)

Output

View has  dict_items([(1, 'Red'), (2, 'Blue'), (3, 'Green')])

Example 2:

Let us take a dictionary with numbers assigned to a list containing names in this example. Now, let us update the value of key 1. As we can see, it automatically updates the view.

#Initializing 
n={1:["Jim","Kim"],2:["John","Tom"],3:["Riya","Siya"]}
v1=n.items()
#Printing 
print("Before update view has ",v1)
#Updating value of key 1
n[1]=["X","Y"]
#Printing 
print("After update view has ",v1)

Output

Before update view has  dict_items([(1, ['Jim', 'Kim']), (2, ['John', 'Tom']), (3, ['Riya', 'Siya'])])
After update view has  dict_items([(1, ['X', 'Y']), (2, ['John', 'Tom']), (3, ['Riya', 'Siya'])])

Example 3:

We will take a dictionary with the department name and student name in this case. Here, we will delete the key “Comp”. As a result, changes are reflected in the view also.

#Initializing 
n={"Comp":"Jim","IT":"Tom","EXTC":"Siya"}
# Using items method
v1=n.items()
#Printing 
print("Before Delete view has ",v1)
del(n["Comp"])
#Printing 
print("After Delete view has ",v1)

Output

Before Delete view has  dict_items([('Comp', 'Jim'), ('IT', 'Tom'), ('EXTC', 'Siya')])
After Delete view has  dict_items([('IT', 'Tom'), ('EXTC', 'Siya')])

Conclusion

The items() method extracts key-value pair from the dictionary as a list. Just because this is a view over the dictionary, all the updates made to the dictionary are also reflected in the view.

References

Happy Learning 🙂

Leave A Comment