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
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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Logistic Regression in Machine Learning Logistic Regression is a supervised machine learning algorithm used for classification problems. Unlike linear regression which predicts continuous values it predicts the probability that an input belongs to a specific class. It is used for binary classification where the output can be one of two po
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read