Python Loop/Iterate Through Dictionary Tutorial

Python for loop can be used to iterate or loop over a dictionary. But as the dictionary is a special data type that consists of key and value pairs or items there are some different ways for iteration. The dictionary items (Key/value pairs), keys, or values can be used for iteration.

Loop/Iterate Through Dictionary with for Loop

The dictionary can be looped with the for loop easily. But there is a problem. Dictionary consist of multiple items and every item consists of key and value pairs. Which one will be a loop in every step. By default, the for loop will iterate over the keys of the given dictionary. Then we can access the value by using the key.

mydict = { "one":"1" , "two":"2" , "three":"3" }

for key in mydict:
   print("Current Key: "+key+" Value: "+mydict[key])

The output will be like below where both the key and value will be printed.

Current Key: one Value: 1
Current Key: two Value: 2
Current Key: three Value: 3

Loop/Iterate Through Dictionary Keys with keys() Method

The dictionary data type provides the keys() method which will return the given dictionary keys as a list in iterable format. We can use these keys in order to iterate over the keys like below.

mydict = { "one":"1" , "two":"2" , "three":"3" }

for key in mydict.keys():
   print("Current Key: "+key+" Value: "+mydict[key])

Loop/Iterate Through Dictionary Values with values()Method

Also, we can loop or iterate over the given dictionary values. The dictionary data type provides the values() method returns only values as a list or iterable format. The for loop can be used to iterate over the returned values easily.

mydict = { "one":"1" , "two":"2" , "three":"3" }

for value in mydict.values():
   print("Current Values "+value)

Loop/Iterate Through Dictionary Items (Both Key and Values) with items() Method

Interestingly the dictionary data type provides the items() method that will return both the key and value as a tuple. So in a for loop, the returned key and value can be set different variables for each step. In the following example, the return key and value are stored in variables named key and value.

mydict = { "one":"1" , "two":"2" , "three":"3" }

for key , value in mydict.items():
   print("Current Key: "+ key +" Value: "+ value)

If you are using Python2 you should use the iteritems() method instead of the items() method. With Python3 iteritems() method is replaced with items() method.

Loop/Iterate Through Dictionary Items (Both Key and Values) In Python2

Even it is losing its base Python2 provides the itermitems() method which returns the item as a key and value pair. We will use the for loop in order to iterate over every item in the dictionary. The iteritems() method returns a tuple with two values one is key and another is value.

mydict = { "one":"1" , "two":"2" , "three":"3" }

for key , value in mydict.iteritems():
   print("Current Key: "+ key +" Value: "+ value)

Leave a Comment