A Guide to Nested Dictionaries in Python with Five Examples

A Guide to Nested Dictionaries in Python with Five Examples

Yes, dictionaries can indeed be nested in Python. Here are five examples demonstrating nested dictionaries:

  1. Nested Dictionary with Simple Values:
nested_dict = {
    'outer_key1': {
        'inner_key1': 'value1',
        'inner_key2': 'value2'
    },
    'outer_key2': {
        'inner_key3': 'value3',
        'inner_key4': 'value4'
    }
}
  1. Nested Dictionary with Lists:
nested_dict_lists = {
    'outer_key1': {
        'inner_key1': [1, 2, 3],
        'inner_key2': [4, 5, 6]
    },
    'outer_key2': {
        'inner_key3': [7, 8, 9],
        'inner_key4': [10, 11, 12]
    }
}
  1. Nested Dictionary with Mixed Data Types:
nested_dict_mixed = {
    'person1': {
        'name': 'Alice',
        'age': 30,
        'address': {
            'city': 'New York',
            'zip': '10001'
        }
    },
    'person2': {
        'name': 'Bob',
        'age': 25,
        'address': {
            'city': 'Los Angeles',
            'zip': '90001'
        }
    }
}
  1. Dynamic Nested Dictionary Creation:
nested_dict_dynamic = {}
nested_dict_dynamic['outer_key1'] = {'inner_key1': 'value1', 'inner_key2': 'value2'}
nested_dict_dynamic['outer_key2'] = {'inner_key3': 'value3', 'inner_key4': 'value4'}
  1. Nested Dictionary within a List:
list_of_dicts = [
    {'name': 'John', 'details': {'age': 30, 'city': 'New York'}},
    {'name': 'Emma', 'details': {'age': 25, 'city': 'Los Angeles'}}
]

In each of these examples, you can see dictionaries nested within other dictionaries, allowing for hierarchical organization of data in Python.