Loading...

Python Nested Dictionaries

Nested Dictionaries in Python

In Python, nested dictionaries are dictionaries that contain other dictionaries as their values. This feature allows you to organize data hierarchically, making it easy to store and access related information. In this lesson, we will explore how to create nested dictionaries, access their items, and loop through them effectively.

1. Understand Nested Dictionaries

A nested dictionary is a dictionary that contains one or more dictionaries within it. This structure is useful for representing complex data relationships.

Example: Creating a Nested Dictionary

python
17 lines
|
75/ 500 tokens
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Defining a nested dictionary to represent family members
my_family = {
    "child1": {
        "name": "Emily",
        "year": 2004
    },
    "child2": {
        "name": "Tobias",
        "year": 2007
    },
    "child3": {
        "name": "Linus",
        "year": 2011
    }
}

print(my_family)
Code Tools

In this example, my_family contains three child dictionaries, each with their own attributes like name and year.

2. Alternative Method: Create Nested Dictionaries

You can also define individual dictionaries first and then combine them into a nested structure.

Example: Creating Individual Dictionaries

python
22 lines
|
94/ 500 tokens
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Defining individual dictionaries for each child
child1 = {
    "name": "Emily",
    "year": 2004
}
child2 = {
    "name": "Tobias",
    "year": 2007
}
child3 = {
    "name": "Linus",
    "year": 2011
}

# Creating a nested dictionary containing the individual dictionaries
my_family = {
    "child1": child1,
    "child2": child2,
    "child3": child3
}

print(my_family)
Code Tools

This method allows for a more modular approach to defining your dictionaries.

3. Access Items in Nested Dictionaries

To access items within a nested dictionary, you can reference the outer dictionary's key, followed by the key of the inner dictionary.

Example: Accessing a Specific Value

python
2 lines
|
21/ 500 tokens
1
2
# Accessing the name of child 2
print(my_family["child2"]["name"])  # Output: Tobias
Code Tools

In this example, we first access child2 and then retrieve the name associated with that child.