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 you should be cautious about the iterated value.

Loop Through Dictionary

The dictionary can be looped with the for loop easily. But there is a problem. Dictionary consist of multiple items and every item consist 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 Through Dictionary Keys

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 Through Dictionary Values

Also, we can loop or iterate over the given dictionary values. The dictionary data type provides the values() method will return only values as a list or iterable format.

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

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

Loop Through Dictionary Items (Both Key and Values)

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)

Leave a Comment