Find value in nested dictionary python

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
  • Creating Nested Dictionaries in Python
  • Accessing Items in Nested Dictionaries in Python
  • Modifying Items in Nested Dictionaries in Python
  • Deleting Items in Nested Dictionaries in Python
  • Iterating Through Nested Dictionaries in Python
  • Converting a Nested Python Dictionary to a Pandas DataFrame
  • Conclusion
  • Additional Resources

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:

  • Python Defaultdict: Overview and Examples
  • Python: Add Key:Value Pair to Dictionary
  • Python: Sort a Dictionary by Values
  • Python Merge Dictionaries – Combine Dictionaries (7 Ways)
  • Python Dictionaries: Official Documentation

How do you get a value from a nested dictionary Python?

Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

How do you iterate through a nested dictionary in Python?

Iterate over all values of a nested dictionary in python For a normal dictionary, we can just call the items() function of dictionary to get an iterable sequence of all key-value pairs.

How do you find the values of a key in a list of dictionaries in Python?

Use a list comprehension to find the values of a key in a list of dictionaries. Use the list comprehension syntax [dict[key] for dict in list_of_dicts] to get a list containing the corresponding value for each occurrence of key in the list of dictionaries list_of_dicts .

How do you find the value of the dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.