Python Guide Sidebar

Dictionaries in Python: Understanding Nested Dictionaries

In Python, dictionaries are powerful data structures that allow you to store key-value pairs. But what if you want to store more complex data, such as a dictionary inside another dictionary? This is where nested dictionaries come into play. A nested dictionary is simply a dictionary where the value of a key is another dictionary.

A nested dictionary is a dictionary inside another dictionary. It allows for organizing data hierarchically, making it useful for representing complex structures. Accessing nested dictionary elements requires chaining keys together.

In this guide, we will explore nested dictionaries, understand how they work, and demonstrate their usage with examples and a mini-project to showcase their practical applications.

What Are Nested Dictionaries?

A nested dictionary is a dictionary that contains other dictionaries as values. This allows you to represent more complex data structures, such as hierarchical information, nested records, or even multi-level data.

For example, consider a dictionary that stores information about different employees in a company, where each employee’s data is stored as a nested dictionary.

employees = {
    "Alice": {"age": 30, "department": "HR", "salary": 50000},
    "Bob": {"age": 25, "department": "Engineering", "salary": 70000},
    "Charlie": {"age": 28, "department": "Marketing", "salary": 60000},
}
In this example, the employees dictionary contains three keys: "Alice", "Bob", and "Charlie". Each of these keys maps to another dictionary containing attributes like age, department, and salary.

How to Access Nested Dictionary Elements

To access elements in a nested dictionary, you can use a series of keys, separated by square brackets. Here’s an example:

employee = employees["Alice"]
print(employee["department"])

Output:

HR

In this case, employees["Alice"] returns the inner dictionary for Alice, and then employee["department"] accesses the value associated with the key "department".

If you want to access a deeper level in the nested dictionary, you can chain the keys like so:

salary = employees["Bob"]["salary"]
print(salary)

Output:

70000

Adding, Modifying, and Removing Items in Nested Dictionaries

Like regular dictionaries, you can add, modify, and remove items in nested dictionaries.

1. Adding Items

To add a new employee with their details:

employees["David"] = {"age": 32, "department": "Finance", "salary": 75000}
2. Modifying Items

To modify an existing employee’s information, such as increasing their salary:

employees["Alice"]["salary"] = 55000

3. Removing Items

To remove an employee’s information:

del employees["Charlie"]

Use Cases for Nested Dictionaries

Nested dictionaries are useful in scenarios where you need to represent hierarchical or multi-level data. Some use cases include:

  1. Storing structured data: For example, storing student records where each student’s data includes multiple fields such as name, age, grades, and contact details.
  2. Representing JSON-like structures: Nested dictionaries are often used to represent data formats like JSON, which commonly include nested objects.
  3. Database-like structures: Nested dictionaries are helpful in storing records with nested properties, such as storing employee details in a company database.

Mini Project: Student Records Management Using Nested Dictionaries

In this mini-project, we will create a system to manage student records. The student records will be stored in a nested dictionary, where each student has multiple attributes such as name, age, and grades.

Features:

  1. Add a new student’s record.
  2. Update an existing student’s information.
  3. Display all student records.
  4. Calculate and display the average grade of a specific student.
# Mini-Project: Student Records Management Using Nested Dictionaries

# Step 1: Initialize the student records dictionary
students = {}

# Step 2: Function to add a new student record
def add_student(name, age, grades):
    students[name] = {"age": age, "grades": grades}

# Step 3: Function to update a student's grades
def update_grades(name, grades):
    if name in students:
        students[name]["grades"] = grades
    else:
        print(f"Student {name} not found.")

# Step 4: Function to display all student records
def display_students():
    for name, info in students.items():
        print(f"Name: {name}, Age: {info['age']}, Grades: {info['grades']}")

# Step 5: Function to calculate the average grade of a student
def average_grade(name):
    if name in students:
        grades = students[name]["grades"]
        avg = sum(grades) / len(grades)
        print(f"Average grade of {name}: {avg:.2f}")
    else:
        print(f"Student {name} not found.")

# Adding student records
add_student("Alice", 20, [85, 90, 92])
add_student("Bob", 22, [78, 88, 91])
add_student("Charlie", 21, [82, 79, 88])

# Displaying all students' records
display_students()

# Updating a student's grades
update_grades("Alice", [87, 92, 94])

# Displaying updated student records
print("\nUpdated Records:")
display_students()

# Calculating the average grade of a student
average_grade("Bob")

Explanation:

  • add_student(): Adds a new student’s record, which includes their name, age, and grades.
  • update_grades(): Updates the grades for an existing student.
  • display_students(): Displays all student records.
  • average_grade(): Calculates the average grade of a specific student.

Output:

Name: Alice, Age: 20, Grades: [85, 90, 92]
Name: Bob, Age: 22, Grades: [78, 88, 91]
Name: Charlie, Age: 21, Grades: [82, 79, 88]

Updated Records:
Name: Alice, Age: 20, Grades: [87, 92, 94]
Name: Bob, Age: 22, Grades: [78, 88, 91]
Name: Charlie, Age: 21, Grades: [82, 79, 88]

Average grade of Bob: 85.57

Explanation:

  • The mini-project demonstrates how to manage student records using nested dictionaries. We added, updated, and displayed records, as well as calculated the average grade of a student.

Interview Questions and Answers


Amazon

Q1: How would you access a value in a nested dictionary in Python?
A1: You can access values in a nested dictionary by chaining keys inside square brackets. For example, employees["Alice"]["salary"] will return the salary of Alice in the nested dictionary.

Google

Q2: What is the primary advantage of using nested dictionaries over other data structures like lists?
A2: The primary advantage of using nested dictionaries is that they allow you to store and access multi-level data efficiently. Nested dictionaries are ideal for representing hierarchical data, like employee records or student grades, where each item has multiple attributes.

Zoho

Q3: Can nested dictionaries be used to represent JSON-like data structures?
A3: Yes, nested dictionaries in Python are perfect for representing JSON-like data structures because both JSON and nested dictionaries follow the key-value pair format. Python’s json module can be used to easily work with JSON data and convert it to nested dictionaries.

Infosys

Q4: How would you modify an existing nested dictionary in Python?
A4: You can modify an existing nested dictionary by accessing the specific key and then updating the value. For example, to update the salary of an employee, you would use employees["Alice"]["salary"] = 55000.

TCS

Q5: How would you remove an entry from a nested dictionary?
A5: To remove an entry from a nested dictionary, you can use the del statement. For example, del employees["Charlie"] will remove Charlie’s record from the dictionary.

Conclusion

Nested dictionaries are a powerful feature in Python that allow you to work with complex, hierarchical data. By using nested dictionaries, you can store multiple attributes for each key and represent more intricate structures such as employee records, student information, and more.

Nested Dictionaries