Skip to content

Python Nested Dictionary: Complete Guide

Python Nested Dictionary Cover Image

In this tutorial, you’ll learn about Python nested dictionaries – dictionaries that are the values of another dictionary. You’ll learn how to create nested dictionaries, access their elements, modify them and more. You’ll also learn how to work with nested dictionaries to convert them to a Pandas DataFrame.

By the end of this tutorial, you’ll have learned:

  • What nested dictionaries are in Python
  • How to create nested dictionaries in Python
  • How to access, modify, and delete elements in nested dictionaries
  • How to convert nested dictionaries to Pandas DataFrames

Python Nested Dictionaries

Python dictionaries are container data structures that hold key:value pairs of information. They’re created by using curly braces {}, where a value can be looked up by accessing its unique key. Let’s take a look at a simple dictionary example:

# A Simple Python Dictionary
user = {
    'Name': 'Nik', 
    'Profession':'datagy'
    }

In the dictionary above, we have an item called user. We can access its values by referencing the dictionary’s keys. Say we wanted to access the dictionary’s value for the key 'Name', we could write:

# Accessing a Dictionary Value
print(user.get('Name')).   # Same as user['Name']

# Returns: Nik

An interesting thing about Python dictionaries is that we can even use other dictionaries as their values. This brings us to the main topic of this article.

Say we wanted to have a dictionary that contained the user information based on someone’s user ID. Let’s create a dictionary that stores the information on multiple users, broken out by an ID:

# Understanding Nested Dictionaries
users = {
    1: {
        'Name': 'Nik', 
        'Profession':'datagy'
        }, 
    2: {
        'Name': 'Kate',
        'Profession': 'Government'
    }    
}

In this example, our earlier dictionary was embedded into the new, larger dictionary. What we’ve done is created a new, nested dictionary. In the following section, we work through how to create nested dictionaries.

Creating Nested Dictionaries in Python

In this section, you’ll learn how to create nested dictionaries. Nested dictionaries are dictionaries that have another dictionary as one or more of their values. Let’s walk through how we can create Python nested dictionaries.

Let’s take a look at an example:

# Creating a Nested Dictionary in Python
users = {}
Nik = {
        'Name': 'Nik', 
        'Profession':'datagy'
    }

Kate = {
        'Name': 'Kate',
        'Profession': 'Government'
}

users[1] = Nik
users[2] = Kate

print(users)

# Returns: {1: {'Name': 'Nik', 'Profession': 'datagy'}, 2: {'Name': 'Kate', 'Profession': 'Government'}}

Let’s break down what we did here:

  1. We instantiated an empty dictionary, users
  2. We created two further dictionaries, Nik and Kate
  3. We then assigned these dictionaries to be the values of the respective keys, 1 and 2, in the users dictionary

Accessing Items in Nested Dictionaries in Python

In this section, you’ll learn how to access items in a nested Python dictionary. In an earlier section, we explored using the .get() method to access items. Let’s see what happens when we try to access an item in a nested dictionary:

# Accessing an Item in a Nested Dictionary
users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

print(users.get(1))

# Returns: {'Name': 'Nik', 'Profession': 'datagy'}

We can see that this returned a dictionary! Since a dictionary was returned we can access an item in the returned dictionary.

Say we wanted to access the 'Name' of user 1, we could write the following:

# Accessing Nested Items in Python Dictionaries
users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

print(users.get(1).get('Name'))

# Returns: Nik 

We can call the .get() method multiple times since we’re accessing a dictionary within a dictionary. In the next section, you’ll learn how to modify items in a nested dictionary.

Modifying Items in Nested Dictionaries in Python

In this section, you’ll learn how to modify items in nested dictionaries. In order to modify items, we use the same process as we would for setting a new item in a dictionary. In this case, we simply need to navigate a little further down, to a key of a nested dictionary.

Say we wanted to change the profession for user 2 to 'Habitat for Humanity'. We can then write:

# Modifying Items in a Nested Dictionary
users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

users[2]['Profession'] = 'Habitat for Humanity'
print(users)

# Returns: 
# {1: {'Name': 'Nik', 'Profession': 'datagy'}, 2: {'Name': 'Kate', 'Profession': 'Habitat for Humanity'}}

In this case, we were able to access the key’s value through direct assignment. If that key didn’t previously exist, then the key (and the value) would have been created.

Deleting Items in Nested Dictionaries in Python

Python dictionaries use the del keyword to delete a key:value pair in a dictionary. In order to do this in a nested dictionary, we simply need to traverse further into the dictionary. Let’s see how we can delete the 'Profession' key from the dictionary 1:

# Deleting an item from a nested dictionary
users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

del users[1]['Profession']

print(users)

# Returns: 
# {1: {'Name': 'Nik'}, 2: {'Name': 'Kate', 'Profession': 'Government'}}

Similarly, we can delete an entire nested dictionary using the same method. Because the nested dictionary is actually just a key:value pair in our broader dictionary, the same method applies. Let’s delete the entire first dictionary 1:

# Deleting an entire nested dictionary
users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

del users[1]

print(users)

# Returns: 
# {2: {'Name': 'Kate', 'Profession': 'Government'}}

In the next section, you’ll learn how to iterate through nested dictionaries in Python.

Iterating Through Nested Dictionaries in Python

In this section, you’ll learn how to iterate through nested dictionaries. This can be helpful when you want to print out the values in the dictionary. We can build a recursive function to handle this. Let’s see what this looks like:

# Iterating through nested dictionaries recursively
users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

def iterate_dict(dict_to_iterate):
    for key, value in dict_to_iterate.items():
        if type(value) == dict:
            print(key)
            iterate_dict(value)
        else:
            print(key + ":" + value)

iterate_dict(users)

# Returns:
# 1
# Name:Nik
# Profession:datagy
# 2
# Name:Kate
# Profession:Government

Converting a Nested Python Dictionary to a Pandas DataFrame

In this final section, you’ll learn how to convert a nested dictionary to a Pandas DataFrame. We can simply pass in the nested dictionary into the DataFrame() constructor. However, Pandas will read the DataFrame with the keys as the indices.

To work around this, we can transpose the DataFrame using the .T method:

# Reading a nested dictionary to a Pandas DataFrame
import pandas as pd

users = {
    1: {'Name': 'Nik', 'Profession': 'datagy'}, 
    2: {'Name': 'Kate', 'Profession': 'Government'}
    }

df = pd.DataFrame(users).T

print(df)

# Returns
#    Name  Profession
# 1   Nik      datagy
# 2  Kate  Government

Conclusion

In this tutorial, you learned about nested dictionaries in Python. You learned what nested dictionaries are. Then you learned how to access, modify, and delete their items. Finally, you learned how to iterate over nested dictionaries as well as how to read them into Pandas DataFrames.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

8 thoughts on “Python Nested Dictionary: Complete Guide”

  1. Hi!

    Im having a hard time creating a nested dictionary already in a nested group. For starters, created a list and divided the line comments based on a special character. So, I have; [‘nissan’,’altima’,’sedan’] and with many more line items..
    Im able to create a dictionary of dict2 = {‘altima’:{‘sedan’,’model below maxima’}. But unable to created the following:
    Option 1
    nest as {‘nissan’:{‘altima’:’sedan’,’model below maxima’}
    Option 2
    dict3 = {‘nissan’,’toyota’} and append the values of dict2 “”nissan related cars” into nissan primary key.

  2. I appreciate the insight you have given me here. The challenges am having is that some values in the nested dictionary are list and am to iterate through elements in these list values.
    Eg d = {‘a1:{‘bk’:[‘aa’,’bbb’,’cc’], ‘pg’:[67,183,213]},’a2′:{‘bk’:[‘zzz’,’mmmm’,’ggg’,’hhh’],’pg’:[300,234,112,,168]}}
    Am to print out all the elements in the nested dict whose values are list and also count the elements.
    Expected output:
    aa
    bbb
    cc
    zzz
    mmmm
    ggg
    hhh
    7

    1. Hi Sunday! Thanks for your comment!

      You could loop over the dictionary, check the value’s type to see if it’s a list, then print the items and the item’s length. Are you filtering the lists at all?

  3. Hey there,
    I’ve got a project with a nested dictionary very similar to yours here. One thing I am trying to do that I can’t quite figure out, is to search for a key, and find others with the same value within the nested dictionary. So to use your example –
    Give it user #1, who’s profession is ‘datagy,’ I need to find all other users who’s profession is also ‘datagy.’ Does that make sense?

Leave a Reply

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