How to Create a Nested Dictionary in Python

1. Introduction

Nested dictionaries in Python are a way to store data that is structured into multiple levels, similar to a tree. This structure is particularly useful when you need to represent a hierarchy or a complex mapping between keys and their associated values. They can be thought of as dictionaries within a dictionary.

Definition

A nested dictionary is a dictionary that contains another dictionary or dictionaries as its values. This structure allows for a more granular level of organizing data. It can represent a wide range of real-world data structures like JSON objects commonly used in web development.

2. Program Steps

1. Define the outer dictionary.

2. Define inner dictionaries for each key in the outer dictionary.

3. Assign the inner dictionaries as values to the keys in the outer dictionary.

4. Access and manipulate data within the nested dictionary.

5. Print the nested dictionary to display its structure.

3. Code Program

# Step 1: Define the outer dictionary
nested_dict = {}

# Step 2: Define inner dictionaries
inner_dict1 = {'key1': 1, 'key2': 2}
inner_dict2 = {'key3': 3, 'key4': 4}

# Step 3: Assign the inner dictionaries to the outer dictionary
nested_dict['dict1'] = inner_dict1
nested_dict['dict2'] = inner_dict2

# Step 4: Accessing data within the nested dictionary
# Accessing the value of 'key1' in 'dict1'
value_key1 = nested_dict['dict1']['key1']

# Step 5: Print the value of 'key1' in 'dict1'
print("Value of 'key1' in 'dict1':", value_key1)

# Step 6: Print the entire nested dictionary
print("Nested dictionary:", nested_dict)

Output:

Value of 'key1' in 'dict1': 1
Nested dictionary: {'dict1': {'key1': 1, 'key2': 2}, 'dict2': {'key3': 3, 'key4': 4}}

Explanation:

1. nested_dict is initialized as an empty dictionary to hold the nested structure.

2. inner_dict1 and inner_dict2 are defined with their respective key-value pairs.

3. These inner dictionaries are then assigned to keys 'dict1' and 'dict2' in the nested_dict.

4. The value of 'key1' in the nested dictionary under 'dict1' is accessed and stored in value_key1.

5. The print statement outputs the value of 'key1' which is 1.

6. The entire nested_dict is printed, showing the structure of the nested dictionaries within the outer dictionary.

Comments