Python – Iterate Dictionary example

Posted on

Dictionary is data structure which store data in key-value pair and widely used in Python programming language. In our previous tutorial, we came up with the example to iterate a list. In this blog, we will demonstrate the examples to iterate dictionary in various ways.

1) Iterate dictionary using keys()

Using keys() method in dictionary we can get all available keys and can get the corresponding value using a loop. Below example demonstrate iteration of dictionary using keys().


2) Iterate dictionary using items()

items() method returns key-value pair which is ideal to iterate dictionary. In case you are using python 2.x items() method would return a list with tuples containing the copied key-value pairs of the dictionary which creates bottle neck for large data set. So, you should prefer the iteritems() method which simply returns an iterator instead of a list. In Python 3.x the iteritems is removed and the items method returns view objects. Below example demonstrate iteration of dictionary using items().


3) Iterate dictionary using iteritems()

In python 2.x, it is preferred method to iterate dictionary.


Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.