The Wayback Machine - https://web.archive.org/web/20240706002731/https://www.geeksforgeeks.org/python-nested-dictionary/
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: 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 - Nested dictionary Combinations
Sometimes, while working with Python dictionaries, we can have a problem in which we need to construct all the combination of dictionary keys with different values. This problem can have application in domains such as gaming and day-day programming. Lets discuss certain way in which we can perform this task. Input : test_dict = {'gfg': {'is' : [6],
3 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a diction
3 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read
Create a Nested Dictionary from Text File Using Python
We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dictionary From Text File using Python: Using json.lo
3 min read
Nested Dictionary to Multiindex Dataframe
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns. A Multiinde
2 min read
Create PySpark dataframe from nested dictionary
In this article, we are going to discuss the creation of Pyspark dataframe from the nested dictionary. We will use the createDataFrame() method from pyspark for creating DataFrame. For this, we will use a list of nested dictionary and extract the pair as a key and value. Select the key, value pairs by mentioning the items() function from the nested
2 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
three90RightbarBannerImg