Python is a powerful, high-level, object-oriented programming language. One of its core data types is the dictionary, which is an unordered collection of items. Each item is stored as a key-value pair. Sometimes, we need to store data in such a way that we can quickly access specific information based on some value. That’s where nested dictionaries come into play.
A nested dictionary is a dictionary inside a dictionary. It’s a collection of dictionaries into one single dictionary.
Creating a Nested Dictionary
Here’s how you can create a nested dictionary in Python:
nested_dict = {
'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}
}
In the above example, dictA
and dictB
are dictionaries themselves, nested inside nested_dict
.
Accessing Elements
Accessing elements in a nested dictionary involves calling the outer dictionary by its key and then the inner dictionary key.
print(nested_dict['dictA']['key_1'])
The above line prints: value_1
Adding Elements
You can add a new dictionary to a nested dictionary by using a new key and assigning it another dictionary.
nested_dict['dictC'] = {}
nested_dict['dictC']['key_3'] = 'value_3'
Now, our nested dictionary looks like this:
{
'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'},
'dictC': {'key_3': 'value_3'}
}
Modifying Elements
Modifying elements in a nested dictionary is similar to accessing elements.
nested_dict['dictA']['key_1'] = 'new_value'
Now, dictA
‘s key_1
has a value of 'new_value'
.
Deleting Elements
We can delete elements in a nested dictionary using the del
keyword.
del nested_dict['dictA']['key_1']
This will delete key_1
from dictA
.
Looping Through a Nested Dictionary
We can loop through a nested dictionary using a for
loop.
for outer_key, inner_dict in nested_dict.items():
print(outer_key)
for inner_key, value in inner_dict.items():
print('\t', inner_key, value)
Example Use Case
One common use case for nested dictionaries is when you’re dealing with complex data structures such as JSON (JavaScript Object Notation) data. JSON data is often nested and can be mapped directly to nested dictionaries in Python.
Let’s consider an example where we have JSON data from a movie database and we want to store it in a Python program for further processing:
# Nested dictionary representing movies data
movies = {
"Star Wars": {
"director": "George Lucas",
"release": 1977,
"characters": {
"Luke Skywalker": {
"actor": "Mark Hamill",
"role": "Protagonist"
},
"Darth Vader": {
"actor": "David Prowse",
"role": "Antagonist"
}
}
},
"The Matrix": {
"director": "Wachowski Brothers",
"release": 1999,
"characters": {
"Neo": {
"actor": "Keanu Reeves",
"role": "Protagonist"
},
"Agent Smith": {
"actor": "Hugo Weaving",
"role": "Antagonist"
}
}
}
}
In this example, the nested dictionary helps us to organize our movie database in a structured and intuitive way. We can easily access and add data. We can also modify information about each movie, its director, release year, characters, actors, and roles:
# Accessing data
print('Actor of Luke Skywalker in Star Wars: ', movies["Star Wars"]["characters"]["Luke Skywalker"]["actor"]) # Prints: Mark Hamill
# Adding new data
movies["The Matrix"]["characters"]["Trinity"] = {
"actor": "Carrie-Anne Moss",
"role": "Supporting Protagonist"
}
print('Added new character Trinity to The Matrix: ', movies["The Matrix"]["characters"]["Trinity"]) # Prints the added character data
# Modifying data
movies["The Matrix"]["characters"]["Neo"]["actor"] = "John Doe"
print('Modified actor for Neo in The Matrix: ', movies["The Matrix"]["characters"]["Neo"]["actor"]) # Prints: John Doe
# Deleting data
del movies["Star Wars"]["characters"]["Darth Vader"]
print('Deleted Darth Vader from Star Wars characters: ', movies["Star Wars"]["characters"]) # Prints Star Wars characters without Darth Vader
# Looping through the dictionary
for movie, details in movies.items():
print('\nMovie:', movie)
for detail, value in details.items():
if isinstance(value, dict): # If value is a dictionary (for characters), loop through it as well
print('\t', detail + ':')
for character, character_info in value.items():
print('\t\t', character + ':', character_info)
else:
print('\t', detail + ':', value)
The code above will print the actor of Luke Skywalker, add a new character to The Matrix, modify the actor for Neo, delete Darth Vader from Star Wars, and then loop through all the movies displaying their details and characters.
In conclusion, nested dictionaries in Python provide a useful data structure to store complex real-world data, and they come with multiple methods to manipulate and interact with the data. Remember to use them wisely, as improperly used nested dictionaries can lead to code that is difficult to understand and maintain.