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'])
Run Code Copy

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'])
Run Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍