Python Nested Dictionary - Dictionary inside Dictionary
Nested Dictionary in Python
Nested Dictionary means dictionary inside a dictionary. As you know, in a key:value pair of a Dictionary, the value could be another dictionary, and if this happens, then we have a nested dictionary.
The following is a simple example for a nested dictionary of depth two.
myDict = {
'foo': {
'a':12,
'b':14
},
'bar': {
'c':12,
'b':14
},
'moo': {
'a':12,
'd':14
},
}
In this tutorial, we will learn how to create a dictionary inside a dictionary, access elements in the deeper Dictionaries.
Create a Nested Dictionary
In the following program, we created a nested dictionary, and printed the nested dictionary and a value corresponding to a key. Also, we confirmed the types of outside dictionary and inside dictionary by printing the type to console output.
Python Program
myDict = {
'foo': {
'a':12,
'b':14
},
'bar': {
'c':12,
'b':14
},
'moo': {
'a':12,
'd':14
},
}
#myDict
print(type(myDict))
print(myDict)
#value of a key
print(type(myDict['foo']))
print(myDict['foo'])
Output
<class 'dict'>
{'foo': {'a': 12, 'b': 14}, 'bar': {'c': 12, 'b': 14}, 'moo': {'a': 12, 'd': 14}}
<class 'dict'>
{'a': 12, 'b': 14}
Access inner elements of Nested Dictionary
We already know how to access a value using key of a Dictionary, which is similar to accessing elements of a one-dimensional array.
Accessing values from a Nested Dictionary is similar to that of accessing elements of a multi-dimensional array, where dimensionality of an array translates to depth of nested dictionary.
In the previous example above, we have created a nested dictionary of depth two. In the following program, we shall access a value from this dictionary with key moo
.
Python Program
myDict = {
'foo': {
'a':12,
'b':14
},
'bar': {
'c':12,
'b':14
},
'moo': {
'a':12,
'd':14
},
}
print(myDict['moo']['a'])
print(myDict['moo']['d'])
Output
12
14
Summary
In this tutorial of Python Examples, we learned what a nested dictionary is, how to create a nested dictionary and how to access values of a nested dictionary at different depths.