How to Make Nested Dictionaries in Python?
Nested dictionaries in Python allow you to create dictionaries within dictionaries, forming a hierarchical data structure.
Each inner dictionary can have its own set of key-value pairs, and the keys of the outer dictionary can map to these inner dictionaries.
# Creating a nested dictionary representing student records
students = {
'student1': {'name': 'Alice', 'age': 22, 'marks': 85},
'student2': {'name': 'Bob', 'age': 21, 'marks': 78},
'student3': {'name': 'Charlie', 'age': 23, 'marks': 92}
}
Syntax
nested_dict = {
‘outer_key1’: {‘inner_key1’: value1, ‘inner_key2’: value2},
‘outer_key2’: {‘inner_key3’: value3, ‘inner_key4’: value4}
}
How to Make Nested Dictionaries in Python
# Creating a nested dictionary representing student records
students = {
'student1': {'name': 'Alice', 'age': 22, 'marks': 85},
'student2': {'name': 'Bob', 'age': 21, 'marks': 78},
'student3': {'name': 'Charlie', 'age': 23, 'marks': 92}
}
# Accessing data from the nested dictionary
print(students['student1']['name']) # Output: 'Alice'
print(students['student2']['marks']) # Output: 78