0
0
Pythonprogramming~5 mins

Nested dictionaries in Python

Choose your learning style9 modes available
Introduction

Nested dictionaries let you store information inside other dictionaries. This helps organize data like a folder inside another folder.

When you want to store details about people, like name and address, inside a main dictionary.
When you keep track of products and each product has multiple properties like price and stock.
When you want to group related settings or options inside a bigger settings dictionary.
Syntax
Python
my_dict = {
    'key1': {
        'nested_key1': 'value1',
        'nested_key2': 'value2'
    },
    'key2': {
        'nested_key3': 'value3'
    }
}

Each value in the main dictionary can be another dictionary.

You access nested values by using multiple keys, like my_dict['key1']['nested_key1'].

Examples
This dictionary stores a person's name and their address as a nested dictionary.
Python
person = {
    'name': 'Alice',
    'address': {
        'city': 'Wonderland',
        'zip': '12345'
    }
}
Each fruit has its own dictionary with price and stock inside the main inventory dictionary.
Python
inventory = {
    'apple': {'price': 0.5, 'stock': 100},
    'banana': {'price': 0.3, 'stock': 150}
}
Sample Program

This program creates a nested dictionary for store items. It then prints the price of the book and the quantity of pens by accessing nested keys.

Python
store = {
    'book': {
        'price': 12.99,
        'quantity': 5
    },
    'pen': {
        'price': 1.5,
        'quantity': 20
    }
}

# Print the price of the book
print(f"Book price: ${store['book']['price']}")

# Print the quantity of pens
print(f"Pen quantity: {store['pen']['quantity']}")
OutputSuccess
Important Notes

You can add or change nested dictionary values by using multiple keys, like store['book']['price'] = 15.99.

Be careful to check if keys exist before accessing nested dictionaries to avoid errors.

Summary

Nested dictionaries help organize complex data by storing dictionaries inside dictionaries.

Access nested values using multiple keys in sequence.

They are useful for grouping related information together clearly.