Creating Nested Dictionaries
There are several ways to create a nested dictionary in Python. Here are a few common approaches:
Initializing a Nested Dictionary Directly
You can create a nested dictionary by defining the inner dictionaries directly within the outer dictionary:
person = {
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"hobbies": ["reading", "hiking", "cooking"]
}
In this example, the "address"
key-value pair is a nested dictionary within the person
dictionary.
Using Dictionary Comprehension
You can also use dictionary comprehension to create a nested dictionary:
data = {
"fruit": ["apple", "banana", "cherry"],
"color": ["red", "yellow", "green"]
}
nested_dict = {fruit: {color: f"{fruit} {color}" for color in data["color"]} for fruit in data["fruit"]}
print(nested_dict)
This will create a nested dictionary where the outer keys are the fruits, and the inner keys are the colors, with the values being a combination of the fruit and color.
Dynamically Adding Nested Dictionaries
You can also create a nested dictionary by dynamically adding key-value pairs to an existing dictionary:
person = {}
person["name"] = "John Doe"
person["age"] = 30
person["address"] = {}
person["address"]["street"] = "123 Main St"
person["address"]["city"] = "Anytown"
person["address"]["state"] = "CA"
person["address"]["zip"] = "12345"
person["hobbies"] = ["reading", "hiking", "cooking"]
This approach allows you to build up the nested dictionary over time, adding new key-value pairs as needed.
Regardless of the method used, creating nested dictionaries in Python is a powerful way to organize and store complex data structures.