|
| Home |
|---|
A nested dictionary is a dictionary that contains another dictionary as its value. This allows you to represent complex and structured data in Python programs.
Nested dictionaries are commonly used to store hierarchical data such as student records, employee information, configuration files and JSON data.
The syntax of a nested dictionary is similar to a normal dictionary, except that one or more values are themselves dictionaries.
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}
print(students)
{'student1': {'name': 'Alice', 'age': 21}, 'student2': {'name': 'Bob', 'age': 22}}
students = {
"student1": {"name": "Alice", "age": 21, "course": "Python"},
"student2": {"name": "Bob", "age": 22, "course": "Data Science"},
"student3": {"name": "Charlie", "age": 23, "course": "Machine Learning"}
}
print(students)
To access elements inside a nested dictionary, you must use multiple keys.
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}
print(students["student1"]["name"])
Alice
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}
print(students["student2"]["age"])
You can add new key-value pairs inside a nested dictionary.
students = {
"student1": {"name": "Alice", "age": 21}
}
students["student1"]["course"] = "Python"
print(students)
students = {
"student1": {"name": "Alice", "age": 21}
}
students["student2"] = {"name": "Bob", "age": 22}
print(students)
students = {
"student1": {"name": "Alice", "age": 21}
}
students["student1"]["age"] = 22
print(students)
You can use loops to iterate through nested dictionaries.
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}
for student, info in students.items():
print(student)
for key, value in info.items():
print(key, ":", value)
products = {
"p1": {"name": "Laptop", "price": 1200, "stock": 10},
"p2": {"name": "Phone", "price": 800, "stock": 20}
}
print(products["p1"]["price"])
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net