Summary: In this tutorial, we will discover different ways to iterate through a normal, nested, and list of dictionaries in Python.

The dictionary is one of the data structures that comes built-in with Python.

It stores the mapping of key and value (as a pair) into a collection and can be nested into other data structures, including itself.

Therefore, accessing each element orderly becomes very important in case of a dictionary.

Let’s see different methods to iterate a dictionary in Python.

Iterate Basic Dictionary

In Python, we can iterate a basic dictionary in 3 different ways:

  1. Iterate directly through keys
  2. Iterate through .keys()
  3. Iterate through .values()
  4. Iterate through .items()

Let’s see an example of each of the methods.

1. Iterate directly through keys

A dictionary in Python by default iterates over the keys. When we use a for loop on a dictionary, Python returns an iterator over its keys.

This iterator is used by the for loop for iterating over the keys of the dictionary object.

Since each key is available inside the body of the loop, we can take the advantage of the indexing operator ([]) to easily access its corresponding value.

countries = {'IN': 'India', 'US': 'United States of America', 'SK': 'South Korea'}

for key in countries:
    print(key, ' <=> ', countries[key])
    
''' 
IN  <=>  India
US  <=>  United States of America
SK  <=>  South Korea
'''

2. Iterate through .keys()

The keys() method of the dictionary returns a view object that contains a list of all the keys available in the dictionary object.

>>> user = {'name': 'Pencil Programmer', 'country': 'India', 'dob': '10/07/1996'}
>>> print(user.keys())
dict_keys(['name', 'country', 'dob'])

This view object in Python is iterable. So, as before, in this method too, we can iterate through the list of keys and fetch all the values of the given dictionary using the [] operator.

user = {'name': 'Pencil Programmer', 'country': 'India', 'dob': '10/07/1996'}

for key in user.keys():
    print(key, ' <=> ', user[key])
    
''' 
name  <=>  Pencil Programmer
country  <=>  India
dob  <=>  10/07/1996
'''

3. Iterate through .values()

Sometimes we would like to iterate only through the values of the given dictionary. In such cases, we should iterate through the .values() of the dictionary object.

The values() method of the dictionary returns an iterable view object that contains the list of available values of the dictionary.

>>> languages = {1 : 'Python', 2: 'C++', 3: 'Java'}
>>> print(languages.values())
dict_values(['Python', 'C++', 'Java'])

We can iterate through this view object using the for loop and access all the values of the given dictionary object.

languages = {1 : 'Python', 2: 'C++', 3: 'Java'}

for value in languages.values():
    print(value)
    
''' 
Python
C++
Java
'''

4. Iterate thorough .items()

When we want to iterate through both key and values of the dictionary, we should use the items() method.

The items() method of the dictionary returns an iterable view object that contains a list of key-value pairs as tuples.

>>> car = {'brand': 'TATA', 'model': 'Nexon', 'power': '4000rpm'}
>>> print(car.items())
dict_items([('brand', 'TATA'), ('model', 'Nexon'), ('power', '4000rpm')])

We can iterate through this list using the for loop and access both key and value at the same.

car = {'brand': 'TATA', 'model': 'Nexon', 'power': '4000rpm'}

for key, value in car.items():
    print(key, ' <=> ', value)
    
''' 
brand  <=>  TATA
model  <=>  Nexon
power  <=>  4000rpm
'''

This is the best approach to iterate through the key-value pairs of a dictionary in Python.

Iterate Nested Dictionary

Iterating a nested dictionary can be tricky, especially if the nesting doesn’t follow any pattern.

For example, in this dictionary not every value is a nested dictionary:

user = {'name': 'Pencil Programmer', 
        'dob': '10/05/1996',
        'address': {
                'city': 'Delhi',
                'pincode': '561002'
            }
        }

Hence, writing nested for loops to iterate such a type of dictionary will not work.

The best way to iterate a nested dictionary is to use recursive iteration.

In recursive iteration, we check if any value is a nested dictionary. If so, we recursively iterate it as a fresh dictionary.

user = {'name': 'Pencil Programmer', 
        'dob': '10/05/1996',
        'address': {
                'city': 'Delhi',
                'pincode': '561002'
            }
        }

#recursive function to iterate a nested dictionary      
def iterate(dictionary, indent=4):
    print('{')
    for key, value in dictionary.items():
        #recurse if the value is a dictionary
        if type(value) is dict:
            print(' '*indent, key, ": ", end='')
            iterate(value, indent+4)
        else:
            print(' '*indent, key, ": ", value)
            
    print(' '*(indent-4), '}')
    
iterate(user)

'''
{
     name :  Pencil Programmer
     dob :  10/05/1996
     address : {
         city :  Delhi
         pincode :  561002
     }
 }
'''

In the recursive function, we are iterating through the .items() of the dictionary using a for loop.

We can also use other types of iteration (as discussed before) and follow the same logic of recursion to iterate a nested dictionary in Python.

Iterate a List of Dictionaries

Python allows nesting of one type of data structure into another.

For example, a list containing multiple dictionaries like the following:

users = [{'name': 'Andrew', 'profession': 'Carpenter'},
         {'name': 'Jacob', 'profession': 'Bus Driver'},
         {'name': 'Pencil Programmer', 'profession': 'NOOB'}]

To iterate such data structure, we should iterate through the outer data structure (list in our case) and then nest the iteration of the inner data structure elements (dictionary).

users = [{'name': 'Andrew', 'profession': 'Carpenter'},
         {'name': 'Jacob', 'profession': 'Bus Driver'},
         {'name': 'Pencil Programmer', 'profession': 'NOOB'}]

#function to iterate and print dictionary line by line   
def iterate_dict(dictionary, ident=4):
    print('{')
    for key, value in dictionary.items():
        print(' '*ident, key, ": ", value)
    print('}')
    
#iterate through the outer list
for dict in users:
    #pass the inner dictionary to the iteration method
    iterate_dict(dict)

'''
{
     name :  Andrew
     profession :  Carpenter
}
{
     name :  Jacob
     profession :  Bus Driver
}
{
     name :  Pencil Programmer
     profession :  NOOB
}
'''

In this example, we are iterating through the given list using the for loop, and passing each dictionary element to the iterate_dict function to iterate over the key-value pairs and print them line by line.

Note: If the list contains nested dictionaries then we have to write iterate_dict as a recursive function (like what we have done before).

Conclusion

In this tutorial, we learned some of the easy and advance ways to iterate over the key and values of a dictionary.

We also learned the recursive method of iterating a nested dictionary in Python and iterated a list of dictionaries.

Leave a Reply

8 + 15 =