Python Nested Dictionary: Building Hierarchical Data Structures
--
Are you looking for a complex data structure for your application? Learn to create a nested dictionary in Python.
Using a nested dictionary in Python is a way to create a hierarchical data structure for your application. In a nested dictionary, the values mapped to keys are also dictionaries. You can build a nested dictionary with as many levels of nesting as you need.
Let’s explore how to create and use this data type!
What is a Nested Dictionary in Python?
A Python nested dictionary is a dictionary that contains one or more dictionaries as values. This is a data structure that allows storing data hierarchically.
How can you create a dictionary with a nested structure in Python?
Below you can see what a nested dictionary looks like:
data = {
'key1': {'inner_key1': 'inner_value1'},
'key2': {'inner_key2': 'inner_value2'}
}
The data dictionary has two keys: key1 and key2. The values associated with key1 and key2 are also dictionaries. That’s why we call this a nested dictionary. We have a dictionary inside a dictionary.
In this example, we have used the names key1 and inner_key1 to distinguish the keys of the outer dictionary from the keys of the inner dictionary.
How to Access Items in a Nested Dictionary with Python
To access a nested dictionary you use the inner and outer dictionary keys sequentially following the order in which they appear in the nested dictionary.
For example, to access the value inner_value2 in the previous dictionary you can use the following syntax:
print(data['key2']['inner_key2'])
[output]
inner_value2
As you can see, we have specified both keys within square brackets in the order in which they appear in the nested dictionary.
How to Access Items in Nested Dictionaries 3 Levels Deep
Let’s see how a nested dictionary works if we go one level deeper.