Nested Dictionary in Python
Nested Dictionary
A dictionary can contain dictionaries, this
is called nested dictionaries.
Example 1
Create a dictionary that contain three dictionaries:
Student = {
"Manoj" :
{
"Roll" : "102",
"Marks" : 300
},
"Monu" :
{
"Roll" : "103",
"Marks" : 326
},
"Sonu" :
{
"Roll" : "104",
"Marks" : 298
}
}
Print(Student)
Output:
{‘Manoj’: {‘Roll’: ‘102’, ‘Marks’: 300}, ‘Monu’: {‘Roll’: ‘103’,
‘Marks’: 326}, ‘Sonu’: {‘Roll’: ‘104’, ‘Marks’: 298}}
Example 2
family = {
"child1" :
{
"name" : "Monu",
"year" : 2004
},
"child2" :
{
"name" : "Rohit",
"year" : 2007
},
"child3" :
{
"name" : "Ashu",
"year" : 2011
}
}
Print(family)
Output:
{'child1': {'name': ‘Monu’, 'year': 2004}, 'child2':
{'name': ‘Rohit’, 'year': 2007}, 'child3': {'name': ‘Ashu’, 'year': 2011}}
Or, if you want to add three dictionaries
into a new dictionary:
Example 3
Create three dictionaries, then create one dictionary that
will contain the other three dictionaries:
child1 = {
"name" : "Monu",
"year" : 2004
}
child2 = {
"name" : "Rohit",
"year" : 2007
}
child3 = {
"name" : "Ashu",
"year" : 2011
}
family = {
"child1" :
child1,
"child2" :
child2,
"child3" :
child3
}
Print(family)
Output:
{'child1': {'name': ‘Monu’, 'year': 2004}, 'child2':
{'name': ‘Rohit’, 'year': 2007}, 'child3': {'name': ‘Ashu’, 'year': 2011}}
Post a Comment