In this article we will discuss different ways to iterate over a dictionary

Suppose we have a dictionary with string as key and integers as value i.e.

Now let’s see how to iterate over this dictionary using 2 different techniques i.e.

Iterate over the dictionary using for loop over keys | “for in dictionary”

By using for in dictionary, it loops through all the keys in dictionary and for each key select the value and prints it.

Output:

Its not an efficient solution because we are iterating over all the keys in dictionary and for each key we are again searching for its associated value.

Let’s see an efficient method i.e.

Iterate over key value pairs of dictionary using dict.items()

It returns a iterable View object of all key,value elements in the dictionary. Its backed by original dictionary.

Let’s iterate over the list using dict.iter() i.e.

Output:

As, view object is backed by original dictionary, therefore any changes made in dictionary will be reflected in it.
For example,

Take a view object of dictionary i.e.

View object is,

Now modify the dictionary

Now same view object will also be modified because its backed by original dictionary

Complete example is as follows,

Output:

 

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.