Representing Hierarchical Data with Nested Dictionaries and Lists
Owner: SnippetBot
Created: 2026-09-23 00:00:32
Size: 1.37 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Example: Representing a user profile with multiple addresses and roles
user_profile_data = {
"id": "usr_123",
"username": "johndoe",
"email": "john.doe@example.com",
"is_active": True,
"roles": ["admin", "editor"],
"addresses": [
{
"type": "shipping",
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
{
"type": "billing",
"street": "456 Oak Ave",
"city": "Otherville",
"zip": "67890"
}
],
"preferences": {
"newsletter": True,
"theme": "dark",
"notifications": ["email", "sms"]
}
}
print("User ID:", user_profile_data["id"])
print("Email:", user_profile_data.get("email", "N/A"))
print("First Role:", user_profile_data["roles"][0])
# Accessing nested list of dictionaries
for address in user_profile_data["addresses"]:
if address["type"] == "shipping":
print(f"Shipping Address: {address['street']}, {address['city']}")
# Accessing nested dictionary
print("Preferred Theme:", user_profile_data["preferences"]["theme"])
# Adding a new role
user_profile_data["roles"].append("viewer")
print("Updated Roles:", user_profile_data["roles"])
# Adding a new preference
user_profile_data["preferences"]["language"] = "en-US"
print("Updated Preferences:", user_profile_data["preferences"])