Back to Blog Home

How To Iterate Through Dictionary In Python

Sandeep Mishra| Python | 6 months, 3 weeks



 

Iterating through a python dictionary is really easy. You can loop over both the keys as well as the values of dictionary. 

 

Lets consider this python dictionary for example:

 

 

heros = {'batman': ‘bruce’ , 'superman': ‘clark’ , 'ironman': ‘tony’} 

 

Now to iterate through the keys of this dictionary 'heroes', we can do something like:

 

for x in heros:

    print(x)

 

 

This will result in output :

 

batman 

superman 

Ironman

 

If you wish to iterate over the values of dictionary:

 

for y in heros.values():

     print(y)

 

This will result in output:


bruce 

clark 

tony

 

Now suppose we need to access both the keys and the values at the same time, then we can use .items() which will help us loop over both keys and values easily. Lets look at the following code :

 

 

for k,v in heros.items():

    print(k +' is alter ego of ' + v)

 

And this will result in output :

 

batman is alterego of bruce

superman is alterego of clark

ironman is alterego of tony 

 

For python 2.x you can also use iteritems() instead of items() to iterate over the dictionary ‘heros’

 

For example 

 

for k,v in heros.iteritems():

     print(k +' is alter ego of ' + v)

 

Will result in output :

 

batman is alterego of bruce

superman is alterego of clark

ironman is alterego of tony

    

 

 

Important point of difference between items() and iteritems()

 

In python 2.x the above examples using items would return a list with tuples containing the copied key-value pairs of the dictionary. So it is recommended that iteritems() is used in python2.x, although .items() will also work fine in python 2.x for iterating through the dictionary.  

 

In Python 3.x the iteritems is removed and the items method returns view objects. The benefit of these view objects compared to the tuples containing copies is that it reflects all the changes of the dict even after the .items() call. 

 



Join 1000+ People Who Subscribe to Weekly Blog Updates

Back to Blog Home