In Python, nested dictionaries are dictionaries that contain other dictionaries as values.
They allow you to store hierarchical, structured data, which can be useful in a variety of applications such as storing records, processing JSON data, and representing real-world objects with multiple attributes.
In this tutorial, we will cover:
- What is a Nested Dictionary?
- Accessing Items in a Nested Dictionary
- Modifying Items in a Nested Dictionary
- Adding Items to a Nested Dictionary
- Removing Items from a Nested Dictionary
- Looping Through a Nested Dictionary
- Examples and Use Cases of Nested Dictionaries
Let’s dive into each concept with explanations and examples.
1. What is a Nested Dictionary?
A nested dictionary is a dictionary where the values can be other dictionaries. This allows you to create complex structures that represent real-world data in a hierarchical way.
Example: Nested Dictionary
students = { "John": {"age": 20, "major": "Computer Science", "GPA": 3.5}, "Alice": {"age": 22, "major": "Mathematics", "GPA": 3.8}, "Bob": {"age": 21, "major": "Physics", "GPA": 3.4} } print(students)
Output:
{ 'John': {'age': 20, 'major': 'Computer Science', 'GPA': 3.5}, 'Alice': {'age': 22, 'major': 'Mathematics', 'GPA': 3.8}, 'Bob': {'age': 21, 'major': 'Physics', 'GPA': 3.4} }
- In this example, the students dictionary contains three keys (“John”, “Alice”, and “Bob”), and each of them has a value that is another dictionary with attributes like age, major, and GPA.
2. Accessing Items in a Nested Dictionary
You can access values in a nested dictionary by using the keys. You access the outer dictionary first and then access the inner dictionary using its keys.
Example 1: Accessing Nested Values
students = { "John": {"age": 20, "major": "Computer Science", "GPA": 3.5}, "Alice": {"age": 22, "major": "Mathematics", "GPA": 3.8} } # Accessing John's age john_age = students["John"]["age"] print(f"John's age: {john_age}") # Accessing Alice's major alice_major = students["Alice"]["major"] print(f"Alice's major: {alice_major}")
Output:
John's age: 20 Alice's major: Mathematics
- In this example, we access the nested dictionaries using a combination of keys (students[“John”][“age”] for John's age).
Example 2: Using .get() to Access Nested Values
You can also use the .get() method to access nested dictionary values. It’s safer because it doesn’t raise a KeyError if the key doesn’t exist.
# Accessing John's GPA using .get() john_gpa = students.get("John", {}).get("GPA", "Not Found") print(f"John's GPA: {john_gpa}") # Trying to access Bob's major (Bob is not in the dictionary) bob_major = students.get("Bob", {}).get("major", "Not Found") print(f"Bob's major: {bob_major}")
Output:
John's GPA: 3.5 Bob's major: Not Found
- In this example, .get() returns “Not Found” if the key doesn’t exist, avoiding a KeyError.
3. Modifying Items in a Nested Dictionary
You can modify values in a nested dictionary by accessing them using their keys and assigning new values.
Example: Modifying Nested Values
students = { "John": {"age": 20, "major": "Computer Science", "GPA": 3.5}, "Alice": {"age": 22, "major": "Mathematics", "GPA": 3.8} } # Modifying John's GPA students["John"]["GPA"] = 3.7 print(f"Updated John's GPA: {students['John']['GPA']}") # Modifying Alice's major students["Alice"]["major"] = "Statistics" print(f"Updated Alice's major: {students['Alice']['major']}")
Output:
Updated John's GPA: 3.7 Updated Alice's major: Statistics
- In this example, we modify the GPA and major for John and Alice by directly assigning new values to the nested dictionary keys.
4. Adding Items to a Nested Dictionary
You can add new items to a nested dictionary by assigning a new dictionary to a key in the outer dictionary.
Example: Adding a New Student
students = { "John": {"age": 20, "major": "Computer Science", "GPA": 3.5}, "Alice": {"age": 22, "major": "Mathematics", "GPA": 3.8} } # Adding a new student Bob students["Bob"] = {"age": 21, "major": "Physics", "GPA": 3.4} print(students)
Output:
{ 'John': {'age': 20, 'major': 'Computer Science', 'GPA': 3.5}, 'Alice': {'age': 22, 'major': 'Mathematics', 'GPA': 3.8}, 'Bob': {'age': 21, 'major': 'Physics', 'GPA': 3.4} }
- In this example, we add a new student (“Bob”) with attributes like age, major, and GPA to the students dictionary.
5. Removing Items from a Nested Dictionary
You can remove items from a nested dictionary using the del statement or the .pop() method.
Example: Removing a Student from the Nested Dictionary
students = { "John": {"age": 20, "major": "Computer Science", "GPA": 3.5}, "Alice": {"age": 22, "major": "Mathematics", "GPA": 3.8}, "Bob": {"age": 21, "major": "Physics", "GPA": 3.4} } # Removing Bob from the dictionary using del del students["Bob"] print(students) # Removing Alice from the dictionary using pop() alice_info = students.pop("Alice") print(f"Alice's information: {alice_info}") print(students)
Output:
{'John': {'age': 20, 'major': 'Computer Science', 'GPA': 3.5}} Alice's information: {'age': 22, 'major': 'Mathematics', 'GPA': 3.8} {'John': {'age': 20, 'major': 'Computer Science', 'GPA': 3.5}}
- In this example, we remove “Bob” using del and remove “Alice” using .pop(), which returns the removed value.
6. Looping Through a Nested Dictionary
You can loop through a nested dictionary using a for loop. You can access both the outer and inner dictionaries during iteration.
Example: Looping Through Nested Dictionary
students = { "John": {"age": 20, "major": "Computer Science", "GPA": 3.5}, "Alice": {"age": 22, "major": "Mathematics", "GPA": 3.8}, "Bob": {"age": 21, "major": "Physics", "GPA": 3.4} } # Looping through the outer dictionary for student, info in students.items(): print(f"Student: {student}") # Looping through the inner dictionary for key, value in info.items(): print(f" {key}: {value}")
Output:
Student: John age: 20 major: Computer Science GPA: 3.5 Student: Alice age: 22 major: Mathematics GPA: 3.8 Student: Bob age: 21 major: Physics GPA: 3.4
- In this example, we loop through both the outer and inner dictionaries, printing the student’s name and their details.
7. Examples and Use Cases of Nested Dictionaries
Example 1: Storing Information About Employees
employees = { "E001": {"name": "John", "position": "Manager", "salary": 70000}, "E002": {"name": "Alice", "position": "Developer", "salary": 65000}, "E003": {"name": "Bob", "position": "Designer", "salary": 60000} } # Accessing employee information for emp_id, details in employees.items(): print(f"Employee ID: {emp_id}") print(f" Name: {details['name']}") print(f" Position: {details['position']}") print(f" Salary: ${details['salary']}")
Output:
Employee ID: E001 Name: John Position: Manager Salary: $70000 Employee ID: E002 Name: Alice Position: Developer Salary: $65000 Employee ID: E003 Name: Bob Position: Designer Salary: $60000
- In this example, we store and access information about employees using a nested dictionary.
Example 2: Representing a Dictionary of Cities with Information
cities = { "New York": {"country": "USA", "population": 8419600}, "Tokyo": {"country": "Japan", "population": 13929286}, "London": {"country": "UK", "population": 8982000} } # Accessing information about cities for city, info in cities.items(): print(f"City: {city}, Country: {info['country']}, Population: {info['population']}")
Output:
City: New York, Country: USA, Population: 8419600 City: Tokyo, Country: Japan, Population: 13929286 City: London, Country: UK, Population: 8982000
- In this example, we store and print details about various cities using nested dictionaries.
Summary of Python Nested Dictionaries:
Concept | Description |
---|---|
Accessing Items | Use multiple keys to access values in a nested dictionary. |
Modifying Items | Modify values by assigning new values to nested dictionary keys. |
Adding Items | Add new dictionaries as values in the outer dictionary. |
Removing Items | Use del or .pop() to remove items from the nested dictionary. |
Looping Through Nested Dicts | Use for loops to iterate over both outer and inner dictionaries. |
Conclusion
Nested dictionaries in Python provide a powerful way to store and manage hierarchical data. In this tutorial, we covered:
- How to create, access, and modify nested dictionaries.
- Adding and removing items from nested dictionaries.
- Looping through nested dictionaries to process the outer and inner elements.
- Examples of real-world use cases, such as managing employee information or storing city details.