• Python Basics

  • Python Variables

  • Operators in Python

  • Conditional Statements in Python

  • Python Lists

  • Python Tuples

  • Python Sets

  • Python Dictionaries

  • Loops in Python

  • Python Arrays and Functions

  • Conclusion

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
1# Defining a nested dictionary to represent family members
2my_family = {
3    "child1": {
4        "name": "Emily",
5        "year": 2004
6    },
7    "child2": {
8        "name": "Tobias",
9        "year": 2007
10    },
11    "child3": {
12        "name": "Linus",
13        "year": 2011
14    }
15}
16
17print(my_family)

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
1# Defining individual dictionaries for each child
2child1 = {
3    "name": "Emily",
4    "year": 2004
5}
6child2 = {
7    "name": "Tobias",
8    "year": 2007
9}
10child3 = {
11    "name": "Linus",
12    "year": 2011
13}
14
15# Creating a nested dictionary containing the individual dictionaries
16my_family = {
17    "child1": child1,
18    "child2": child2,
19    "child3": child3
20}
21
22print(my_family)

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
1# Accessing the name of child 2
2print(my_family["child2"]["name"])  # Output: Tobias

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

Frequently Asked Questions