Open In App

Python Nested Dictionary

Last Updated : 10 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type.

What is Python in Nested Dictionary?

Nesting Dictionary means putting a dictionary inside another dictionary. Nesting is of great use as the kind of information we can model in programs is expanded greatly.

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

Example

Python3




# As shown in image
 
# Creating a Nested Dictionary
Dict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}


Illustration using Image

Python Nested Dictionary

 

Creating a Nested Dictionary

In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces. 

Python3




# Empty nested dictionary
Dict = { 'Dict1': { },
        'Dict2': { }}
print("Nested dictionary 1-")
print(Dict)
 
# Nested dictionary having same keys
Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},
        'Dict2': {'name': 'Bob', 'age': '25'}}
print("\nNested dictionary 2-")
print(Dict)
 
# Nested dictionary of mixed dictionary keys
Dict = { 'Dict1': {1: 'G', 2: 'F', 3: 'G'},
        'Dict2': {'Name': 'Geeks', 1: [1, 2]} }
print("\nNested dictionary 3-")
print(Dict)


Output:

Nested dictionary 1-
{'Dict1': {}, 'Dict2': {}}

Nested dictionary 2-
{'Dict1': {'name': 'Ali', 'age': '19'}, 'Dict2': {'name': 'Bob', 'age': '25'}}

Nested dictionary 3-
{'Dict1': {1: 'G', 2: 'F', 3: 'G'}, 'Dict2': {1: [1, 2], 'Name': 'Geeks'}}

Adding Elements to a Nested Dictionary

The 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’}.

Python3




Dict = { }
print("Initial nested dictionary:-")
print(Dict)
 
Dict['Dict1'] = {}
 
# Adding elements one at a time
Dict['Dict1']['name'] = 'Bob'
Dict['Dict1']['age'] = 21
print("\nAfter adding dictionary Dict1")
print(Dict)
 
# Adding whole dictionary
Dict['Dict2'] = {'name': 'Cara', 'age': 25}
print("\nAfter adding dictionary Dict1")
print(Dict)


Output:

Initial nested dictionary:-
{}

After adding dictionary Dict1
{'Dict1': {'age': 21, 'name': 'Bob'}}

After adding dictionary Dict1
{'Dict1': {'age': 21, 'name': 'Bob'}, 'Dict2': {'age': 25, 'name': 'Cara'}}

Access Elements of a Nested Dictionary

In order to access the value of any key in the nested dictionary, use indexing [] syntax.

Python3




# Nested dictionary having same keys
Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},
        'Dict2': {'name': 'Bob', 'age': '25'}}
 
# Prints value corresponding to key 'name' in Dict1
print(Dict['Dict1']['name'])
 
# Prints value corresponding to key 'age' in Dict2
print(Dict['Dict2']['age'])


Output: 

Ali
25

Deleting Dictionaries from a Nested Dictionary

Deletion of dictionaries from a nested dictionary can be done either by using the Python del keyword or by using pop() function.

Python3




Dict = {'Dict1': {'name': 'Ali', 'age': 19},
        'Dict2': {'name': 'Bob', 'age': 21}}
print("Initial nested dictionary:-")
print(Dict)
 
# Deleting dictionary using del keyword
print("\nDeleting Dict2:-")
del Dict['Dict2']
print(Dict)
 
# Deleting dictionary using pop function
print("\nDeleting Dict1:-")
Dict.pop('Dict1')
print (Dict)


Output: 

Initial nested dictionary:-
{'Dict2': {'name': 'Bob', 'age': 21}, 'Dict1': {'name': 'Ali', 'age': 19}}

Deleting Dict2:-
{'Dict1': {'name': 'Ali', 'age': 19}}

Deleting Dict1:-
{}


Similar Reads

Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Sum values for each key in nested dictionary
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects. Code #1: Find sum of sharpness values using sum() function Step-by-step approach:
2 min read
Python | Remove duplicate dictionaries from nested dictionary
Given a nested dictionary, the task is to remove duplicate dictionaries from the dictionary. Given below are few methods to complete the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{
6 min read
Python | Sort nested dictionary by key
Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Method #1 : Using OrderedDict() + sorted() This task
4 min read
Python | Add keys to nested dictionary
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today's world with advent of NoSQL databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using for loop Step-by-step
5 min read
Python | Safe access nested dictionary keys
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let's discuss certain ways to safely get the nested available key in dictionary. Method #1 : Using nested ge
3 min read
Python: Update Nested Dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Refer to the below article to get the idea about dictionaries: Python Dictionary Nested Dictionary: The nested diction
6 min read
Python - Flatten Nested Dictionary to Matrix
Sometimes, while working with data, we can have a problem in which we need to convert a nested dictionary into Matrix, each nesting comprising the different rows in the matrix. This can have applications in many data domains. Let us discuss certain ways in which this task can be performed. Method #1 : Using loop + zip() + map() The combination of t
5 min read
three90RightbarBannerImg