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.

'''
Creating Dictionaries with string as key and int as value
'''                                  
wordFrequency = {
    "Hello" : 7,
    "hi" : 10,
    "there" : 45,
    "at" : 23,
    "this" : 77
    }

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.

'''
Iterate over the dictionary using for loop
'''
for key in wordFrequency:
    value = wordFrequency[key]
    print(key, " :: ", value)

Output:
Hello  ::  7
there  ::  45
at  ::  23
this  ::  77
hi  ::  10

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()

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.

'''
Iterate over the dictionary using items()
'''    
for key , value in wordFrequency.items():
    print(key, " :: ", value)

Output:
Hello  ::  7
there  ::  45
at  ::  23
this  ::  77
hi  ::  10

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.

# Take a dictionary view 
dictView =  wordFrequency.items()

View object is,
dict_items([('this', 77), ('hi', 10), ('Hello', 7), ('there', 45), ('at', 23)])

Now modify the dictionary
wordFrequency["hi"] = 90

Now same view object will also be modified because its backed by original dictionary
dict_items([('this', 77), ('hi', 90), ('Hello', 7), ('there', 45), ('at', 23)])

Python Dictionary Tutorial - Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows,

def main():

    '''
    Creating Dictionaries with string as key and int as value
    '''                                  
    wordFrequency = {
        "Hello" : 7,
        "hi" : 10,
        "there" : 45,
        "at" : 23,
        "this" : 77
        }

    '''
    Iterate over the dictionary using for loop
    '''
    for key in wordFrequency:
        value = wordFrequency[key]
        print(key, " :: ", value)
    
    print("**************")    
    
    '''
    Iterate over the dictionary using items()
    '''    
    for key , value in wordFrequency.items():
        print(key, " :: ", value)    

    # Take a dictionary view 
    dictView =  wordFrequency.items()
    
    print("Dictionary View before modification : ", dictView, sep ="\n")
    
    # Modify the dictionary
    wordFrequency["hi"] = 90
    
    print("Dictionary View after modification : ", dictView, sep ="\n")
        
if __name__ == "__main__":
    main()

Output:
there  ::  45
hi  ::  10
this  ::  77
at  ::  23
Hello  ::  7
**************
there  ::  45
hi  ::  10
this  ::  77
at  ::  23
Hello  ::  7
Dictionary View before modification : 
dict_items([('there', 45), ('hi', 10), ('this', 77), ('at', 23), ('Hello', 7)])
Dictionary View after modification : 
dict_items([('there', 45), ('hi', 90), ('this', 77), ('at', 23), ('Hello', 7)])

 

Join a list of 2000+ Programmers for latest Tips & Tutorials