How to get value from nested dictionary in python

Learn about Nested Dictionary in Python.

You must be familiar with dictionaries in Python. However, before moving ahead with the agenda of our article, let us get a quick recap of the dictionary in Python.

Dictionary in Python is one of the most popular data structures. Dictionaries are used to store data in a "key-value" pair format. The keys are always unique within a dictionary. The values of the Python dictionary may or may not be unique. We can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value.

How to get value from nested dictionary in python

So, what are Nested Dictionaries?

In Python, a nested dictionary is a dictionary inside a dictionary. Basically, it is a collection of dictionaries kept inside a single dictionary.

Nested dictionaries are one of the ways to represent and store structured information (similar to some ‘records’ in other languages).

How to get value from nested dictionary in python

Below given is a simple example of a nested dictionary.

my_dict = { 'dict1': {'key_A': 'value_A'},
        'dict2': {'key_B': 'value_B'}}

We shall understand the above code in depth going further.

Creating a Nested Dictionary

Creating a nested dictionary is very similar to how we create any other normal dictionary. There is a very basic difference that, in the nested dictionary, the value can also be a dictionary.

Let us understand this clearly through an example. Suppose, we have kept the records of 3 students in a dictionary. Say, an individual student has the following properties: Name, Class, and Roll No.

How to get value from nested dictionary in python

We can represent this very clearly through a nested dictionary.

school = {'student1': {'name': 'Ace', 'roll': '10', 'class': '5'},
     'student2': {'name': 'Bob', 'roll': '15', 'class': '5'},
     'student3': {'name': 'Ron', 'roll': '18', 'class': '6'}}

Explanation: In the above example, we have created a dictionary named "school". This is a nested dictionary which has the student index as the key and the student's properties like name, roll and class are the values of the keys. But here, please note that every key is mapped to a value which itself is a dictionary. In simple words, the values in this dictionary are the dictionary itself. So, this is how we create a nested dictionary.

Let us also learn about an important way of creating nested dictionaries.

The dict() Constructor

There is a "type constructor" called dict() in Python, that can be used to create python dictionaries from keyword arguments or any kind of key-value pairs. It can even create a dictionary from another dictionary and keyword arguments.

These terms might not be making any sense to you, hence let us understand how is the dict() constructor used to create a nested dictionary through easy examples.

1. Keyword Arguments to Nested Dictionary

To create a nested dictionary, we can simply pass our dictionary key : value pair as keyword arguments to the dict() constructor. For example, look at the code below --


# using the dict constructor to convert 
# Keyword Arguments to nested dictionary
school = dict('student1'= {'name': 'Ace', 'roll': '10', 'class': '5'},
     'student2'= {'name': 'Bob', 'roll': '15', 'class': '5'},
     'student3'= {'name': 'Ron', 'roll': '18', 'class': '6'})

print(school)

Output:

    {'student1': {'name': 'Ace', 'roll': '10', 'class': '5'},
     'student2': {'name': 'Bob', 'roll': '15', 'class': '5'},
     'student3': {'name': 'Ron', 'roll': '18', 'class': '6'}}

In the above example, please note that we have enclosed our dictionary into round brackets '()' and passed it to the dict() constructor --

#using the dict() constructor
dict('a'={...},'b'={...})

As a result, the dict() constructor transformed the above keyword arguments into nested dictionary.

2. Using zip() Method in Python

The zip() function takes some iterables (can be zero or more), sums them up in a tuple, and return them. We can use zip to combine separate lists of keys and values. We can also pass the list of keys and values to the zip() function dynamically at runtime.

# student list contains the student indexes
studentList = ['student1', 'student2', 'student3']

# studentinfo contains the information regarding the students
studentInfo = ['student1'= {'name': 'Ace', 'roll': '10', 'class': '5'},
     'student2'= {'name': 'Bob', 'roll': '15', 'class': '5'},
     'student3'= {'name': 'Ron', 'roll': '18', 'class': '6'}]

# zipping up the studentlist and studentinfo list into
# a dictionary using the zip() method
school = dic(zip(studentList, studentInfo))
print(school)

Output:

    {'student1': {'name': 'Ace', 'roll': '10', 'class': '5'},
     'student2': {'name': 'Bob', 'roll': '15', 'class': '5'},
     'student3': {'name': 'Ron', 'roll': '18', 'class': '6'}}

3. Using Python Dictionary fromkeys() Method

The fromkeys() method in python dictionary creates a new dictionary with the default value for all specified keys. In case we do not specify any default value then, all the keys are set to None.

Code:

#Syntax
dict.fromkeys(keys,value)

# Example
# Create a dictionary and set default value 'Employee' for all keys
emp = dict.fromkeys(['A', 'B', 'C'], 'Employee')
print(emp)

Output:

{'A': 'Employee', 'B': 'Employee', 'C': 'Employee'}

We can use the dict.fromkeys() method to create a nested dictionary with some default values. For example, consider the given code below --

Code:

# student list contains the student indexes
studentList = ['student1', 'student2', 'student3']

# studentinfo contains the default properties that should  # be present for a student
studentDefault = {'name':'','roll':'','class':''}

# passing the studentList and studentDefault 
# to dic.fromkeys for creating nested dictionary
school = dic.fromkeys(studentList, studentDefault)
print(school)

Output:

    {'student1': {'name': '', 'roll': '', 'class': ''},
     'student2': {'name': '', 'roll': '', 'class': ''},
     'student3': {'name': '', 'roll': '', 'class': ''}}

Explanation: As we explained above, the fromkeys() created a dictionary based on the keys and default the values we passed to it.

Access Nested Dictionary Items

We can access the items of a dictionary by specifying the key of the dictionary and key of the nested dictionary into square brackets. For example, consider the below code:

Code:

school = {'student1': {'name': 'Ace', 'roll': '10', 'class': '5'},
     'student2': {'name': 'Bob', 'roll': '15', 'class': '5'},
     'student3': {'name': 'Ron', 'roll': '18', 'class': '9'}}

print(school['student2']['name'])
# prints Bob
print(school['student3']['roll'])
# prints 18

Output:

Exception: If we try to access any key-value pair that doesn't exist in our dictionary, we will get a keyerror.

Code:

print(school['student1']['section'])
# it will raise a keyerror because, there is no key 
# named 'section' in our dictionary

Output:

However, we can prevent our codes to fall into any key error. This can be done using the special dictionary get() method. The get() method returns the value for the key if the key is in the dictionary, otherwise, it returns None. Hence, we never get the keyError if we use this method.

Code:

print(school['student1'].get(['section'])) #None
# it will not raise a keyerror because, 
# we have used the get method

Output:

Deleting Dictionaries from a Nested Dictionary

Deleting a dictionary from a nested dictionary is a straightforward operation, for which, we can use python's del keyword. Another way to delete a dictionary is, by using the pop() method in python.

1. Using the pop() Method

pop() is generally used when we want the value of the dictionary after deleting it. So, pop() returns a value. For example, look at the code below:

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }

# using pop function
val = my_dict.pop('A')
print("Deleted value is: ",val) #{'x':1,'y':2,'z':3}
print("Dictionary after popping value is: ",my_dict)

Output:

Deleted value is: {'x':1,'y':2,'z':3}

Dictionary after popping value is: {
    'B': {'x':4,'y':5,'z':6},
    'C': {'x':7,'y':8,'z':9},
}

2. Using del Keyword

Another way to delete a dictionary is by using del keyword in Python. This is generally used when we do not want the value which is deleted. For example, look at the code below:

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }

# using del keyword
del my_dict['A']
print("Dictionary after deleting value is: ",my_dict)

Output:

Dictionary after deleting value is: {
    'B': {'x':4,'y':5,'z':6}
    'C': {'x':7,'y':8,'z':9}
}

Add or Update Element to a Nested Dictionary

We can add or update the elements of a nested dictionary very simply. However, there is a difference when we are trying to add a new key to our dictionary or update any existing key. The difference is --

  • If the key is already present in the dictionary, value gets updated.
  • If the key is not present in the dictionary, a new key: value pair is added to the dictionary.

Let us understand these in-depth below through code. If we add a key-value pair to a nested dictionary, with a key that is already present into the original nested dictionary, then the old value gets updated. For example, look at the code below:

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }


my_dict['C'] = {'x': 11, 'y': 12, 'z':13}
print(my_dict)

Output:

        {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x': 11, 'y': 12, 'z':13}
          }

Explanation: In the above example, we try to add an element to the dictionary, but please note that the key already exists in our dictionary. Since the key is already present in the dictionary, its value is replaced by the new one.

Let us now see by adding a new element to our dictionary.

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }


my_dict['D'] = {'x': 11, 'y': 12, 'z':13}
print(my_dict)

Output:

{
   'A': {'x':1,'y':2,'z':3},
   'B': {'x':4,'y':5,'z':6},
   'C': {'x':7,'y':8,'z':9},
   'D': {'x': 11, 'y': 12, 'z':13}
  }

In this example, we have used a new key so it directly gets added to our nested dictionary. And, hence the dictionary has a new element added. So this is a major difference, if our key already exists in our dictionary then our dictionary gets updated, otherwise, a new key-value pair is added to the dictionary.

Delete Elements from a Nested Dictionary

We have already seen how to delete a dictionary item from a nested dictionary. Here we will learn how can we remove a single element or value from a nested dictionary.

Removing value from a nested dictionary is very similar to removing a dictionary item itself. There are mainly 2 ways(precisely 3). Let us learn each of them.

Using del Keyword in Python

We can use the del keyword to delete an element from our nested dictionary. However, del does not return anything hence we cannot retrieve the element which we have deleted using it. Let us see an example to demonstrate its usage.

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }

# using del keyword
del my_dict['A']['x']   #deletes 'x':1
del my_dict['B']['y']   #deletes 'y':5
del my_dict['C']['z']   #deletes 'z':9
print("Dictionary after deleting value is: \n {}".format(my_dict))

Output:

Dictionary after deleting value is: 
{'A': {'y': 2, 'z': 3}, 'B': {'x': 4, 'z': 6}, 'C': {'x': 7, 'y': 8}}

Explanation: In the above example, we used the del keyword to delete the value from the dictionary. We fetched the value of the dictionary using the key. We can also use indexing to delete elements at any particular index.

Using pop() Method

We can use the pop() method to delete an element from our nested dictionary. Unlike the del keyword, pop() returns the value whenever it deletes any item. So, it is recommended to use the pop() method whenever we want to fetch the value of the element we deleted. Below given is an example of using pop to delete elements.

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }

# using pop method
a = my_dict['A'].pop('x')   #pops 'x':1
print("a = ",a)
b = my_dict['A'].pop('z')   #pops 'z':3
print("b = ",b)
c = my_dict['B'].pop('y')   #pops 'y':5
print("c = ",c)
print("Dictionary after deleting value is: \n {}".format(my_dict))

Output:

a =  1
b =  3
c =  5
Dictionary after deleting value is: 
{'A': {'y': 2}, 'B': {'x': 4, 'z': 6}, 'C': {'x': 7, 'y': 8, 'z': 9}}

Explanation: As explained above, we fetch the dictionary elements values to be deleted using the key of the nested dictionary. Later, we store the values of the elements that are popped using pop().

Iterate through Each Element in a Nested Dictionary

In normal dictionaries, we can iterate over the dictionary using dict.items(). But, this is not the case with nested dictionaries. Here, we can have dictionaries within dictionaries and hence we have to go to one more level for iterating through their values.

We can iterate in a nested dictionary using the nested for-loop. Let us look at our code to understand it better.

Code:

my_dict = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
           'C': {'x':7,'y':8,'z':9}
          }

for key, val in my_dict.items():
    print("Key : {}".format(key))
    for nested_key, nested_val in val.items():
        print("{} : {}".format(nested_key,nested_val))

Output:

Key : A
x : 1
y : 2
z : 3
Key : B
x : 4
y : 5
z : 6
Key : C
x : 7
y : 8
z : 9

Explanation: In the above example, we first iterate over the dictionary items, which in turn gives us the key value pair keykey, valval . Now, the resulting value valval is another dictionary. Hence, we iterate over val.items() to get nestedKeynestedKey and neste dValnestedVal. This code will work fine if we have only one level of nested dictionary. For n-levels of the nested dictionary, this is not the appropriate way.

In this article, we learned how can we iterate over a nested dictionary which is 1 level nested (only 1 dictionary inside a dictionary). However, there are cases where we might have n-levels of nested dictionaries. For them, the simplest way to iterate is through recursively calling it's each level of nesting. Please note, that the n-level nested dictionary is not under the scope of this article.

Merge Two Nested Dictionaries

Two nested dictionaries can be merged using the update() method in Python.

update method():

The update() method updates the dictionary with the key: value pairs from the element.

  • If the key is already present in the dictionary, the value gets updated.
  • If the key is not present in the dictionary, a new key: value pair is added to the dictionary.

Syntax:

dictionary.update(element)

Let us see the code below to update any dictionary.

Code:

my_dict1 = {
           'A': {'x':1,'y':2,'z':3},
           'B': {'x':4,'y':5,'z':6},
          }
          
my_dict2 = {
           'D': {'x':11,'y':12,'z':13},
           'B': {'x':14,'y':15,'z':16},
          }

# using update to update our dictionary
my_dict1.update(my_dict2)
print(my_dict1)

Output:

{'A': {'x': 1, 'y': 2, 'z': 3},
 'B': {'x': 14, 'y': 15, 'z': 16},
 'D': {'x': 11, 'y': 12, 'z': 13}}

Explanation: In the above example, we update the my_dict1 dictionary with my_dict2 dictionary. While doing so, whichever key is already present in my_dict1 gets overwritten by key of my_dict2. And, if the key is not present, then a new key gets added. For example, BB key gets updated in the my_dict1 dictionary. And new key DD is added in my_dict1, because it was not already present.

Important conclusions:

  1. update() method blindly overwrites values of the same key if there’s a clash(or equal key in 2 dictionaries).
  2. update() method updates the dictionary directly, it does not return anything.

This article included all the major points you need to know to get a brief idea about nested dictionaries in Python. You may also refer to the below scaler articles to know more about Dictionary in Python. Also, the prerequisite to this article is dictionary in Python.

  • List in Python
  • Dictionary in Python

Conclusion

In this article, we learnt about nested dictionaries in Python. Let us recap what we learned throughout.

  1. A dictionary can contain another dictionary, which in turn can contain dictionaries themselves, which are nested dictionary in python.
  2. We can create a nested dictionary in python using the dict() Constructor
  3. We can access a nested dictionary in python using either the index or the keys of the dictionary.
  4. We can add or update any item by referring to its key and assigning a value. If the key is already present in the dictionary, its value is replaced by the new one.
  5. Removing dictionary items can be performed using del and pop() method in Python.
  6. Iterating of nested dictionary in python can be performed by using a nested for loop.
  7. Merging of nested dictionary in python can be done using update().

How do you get a specific value from a nested dictionary in 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 I extract a dictionary value?

How to Extract Dictionary Values as a List.
(1) Using a list() function: my_list = list(my_dict.values()).
(2) Using a List Comprehension: my_list = [i for i in my_dict.values()].
(3) Using For Loop: my_list = [] for i in my_dict.values(): my_list.append(i).

How do you make a nested dictionary dynamically in Python?

Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.

What is nested dictionary in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.