Nested Dictonary
Nested Dictonary
In Python, a dictionary can also contain many dictionaries. When we put a dictionary inside another
dictionary, then it is called nested dictionary in Python.
In other words, a nested dictionary is the process of storing multiple dictionaries inside a dictionary.
In the real world of technology, a nested dictionary is useful when we are processing and
transforming data from one format into the other.
Nested dictionaries can be modified, added, or deleted in the same way as regular dictionaries.
Python provides powerful methods like get(), items(), and update() that work with nested
dictionaries as well.
We can create or define a nested dictionary by putting comma-separated dictionaries within curly
braces. The general syntax to create a nested dictionary in Python is as:
gradebook = {
"Mahika" : {
"Maths" : "A",
"Science" : "A++",
"English" : "A",
"GDP" : 9.8
},
"Ravina" : {
"Maths" : "A",
"Science" : "A",
"English" : "B",
"GDP" : 9.3
},
"Kritika" : {
"Maths" : "B",
"Science" : "C",
"English" : "A",
"GDP" : 8.5
In this example, gradebook is the name of nested dictionary with the dictionary Mahika, Ravina, and
Kritika. Dictionaries Mahika, Ravina, and Kritika are separate dictionaries that contain their key-value
pairs. So, we can say that nested dictionary is a collection of dictionaries into a single dictionary.
Example
myfamily = {
"child1" : {
"name" : "A",
"year" : 2004
},
"child2" : {
"name" : "B",
"year" : 2007
},
"child3" : {
"name" : "C",
"year" : 2011
print(myfamily)
Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
child2 = {
"name" : "Tobias",
"year" : 2007
child3 = {
"name" : "Linus",
"year" : 2011
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
print(myfamily)
The get() method returns the value for key if key is in the dictionary.
You can also specify the default parameter that will be returned if the specified key is not found.
If default is not specified, it returns None. Therefore, this method never raises a KeyError.
It’s an easy way of getting the value of a key from a dictionary without raising an error.
Basic Examples
get() method is generally used to get the value for the specific key.
print(D.get('name'))
# Prints Bharat
print(D.get('job'))
# Prints None
print(D.get('job', 'Developer'))
# Prints Manager
But if key is not in the dictionary, the method returns specified default.
print(D.get('job','Developer'))
# Prints Developer