0
0
PythonHow-ToBeginner · 3 min read

How to Create Nested Dictionary in Python: Simple Guide

To create a nested dictionary in Python, use a dictionary where the values are also dictionaries, like {'key1': {'subkey1': value}}. You can define it directly or build it step-by-step by assigning dictionaries as values.
📐

Syntax

A nested dictionary is a dictionary where each value can be another dictionary. The general syntax looks like this:

  • {'key1': {'subkey1': value1, 'subkey2': value2}, 'key2': {'subkey3': value3}}
  • Each key points to another dictionary as its value.
python
nested_dict = {
    'outer_key1': {
        'inner_key1': 'value1',
        'inner_key2': 'value2'
    },
    'outer_key2': {
        'inner_key3': 'value3'
    }
}
💻

Example

This example shows how to create a nested dictionary and access its values.

python
nested_dict = {
    'fruits': {
        'apple': 3,
        'banana': 5
    },
    'vegetables': {
        'carrot': 4,
        'lettuce': 2
    }
}

# Accessing nested values
apple_count = nested_dict['fruits']['apple']
lettuce_count = nested_dict['vegetables']['lettuce']

print(f"Apples: {apple_count}")
print(f"Lettuce: {lettuce_count}")
Output
Apples: 3 Lettuce: 2
⚠️

Common Pitfalls

One common mistake is trying to access a nested key that does not exist, which causes a KeyError. Another is assigning mutable default values incorrectly when using functions.

Example of wrong and right ways to add nested dictionaries:

python
# Wrong way: overwriting inner dictionary
nested_dict = {}
nested_dict['outer'] = {}
nested_dict['outer']['inner'] = 1
nested_dict['outer'] = {'inner2': 2}  # This overwrites previous inner dictionary

# Right way: update inner dictionary instead
nested_dict = {}
nested_dict['outer'] = {}
nested_dict['outer']['inner'] = 1
nested_dict['outer']['inner2'] = 2

print(nested_dict)
Output
{'outer': {'inner': 1, 'inner2': 2}}
📊

Quick Reference

Tips for working with nested dictionaries:

  • Use dict[key][subkey] to access nested values.
  • Use dict.get(key, {}) to avoid errors when keys might be missing.
  • To add nested keys, assign dictionaries or update existing ones carefully.
  • Consider collections.defaultdict for automatic nested dictionary creation.

Key Takeaways

A nested dictionary is a dictionary with dictionaries as values.
Access nested values using multiple keys like dict[key1][key2].
Avoid KeyError by checking keys or using get() with defaults.
Add or update nested dictionaries carefully to prevent overwriting.
Use defaultdict for easier nested dictionary creation when needed.