Python - Nested Dictionaries

Hello there, aspiring coders! Today, we're going to dive into the fascinating world of nested dictionaries in Python. Don't worry if you're new to programming - I'll guide you through this topic step by step, just like I've done for countless students over my years of teaching. So, grab your favorite beverage, get comfortable, and let's embark on this Python adventure together!

Python - Nested Dictionaries

Nested Dictionaries

What are Nested Dictionaries?

Imagine you have a big box (the main dictionary), and inside this box, you have several smaller boxes (the nested dictionaries). Each of these smaller boxes can contain various items (key-value pairs). That's essentially what a nested dictionary is - a dictionary within a dictionary.

Let's start with a simple example:

student = {
    "name": "Alice",
    "age": 20,
    "grades": {
        "math": 95,
        "science": 88,
        "history": 92
    }
}

In this example, student is our main dictionary. It contains basic information about Alice, including a nested dictionary grades that holds her scores in different subjects.

Creating a Nested Dictionary in Python

Creating a nested dictionary is similar to creating a regular dictionary, but you're adding another dictionary as a value. Let's create a more complex example - a school directory:

school = {
    "Grade 9": {
        "Alice": {
            "age": 14,
            "subjects": ["Math", "Science", "English"]
        },
        "Bob": {
            "age": 15,
            "subjects": ["History", "Art", "PE"]
        }
    },
    "Grade 10": {
        "Charlie": {
            "age": 16,
            "subjects": ["Physics", "Chemistry", "Biology"]
        }
    }
}

Here, we have a main dictionary school, which contains grade levels as keys. Each grade level is another dictionary containing student names as keys. Each student then has their own dictionary with personal information.

Adding Items to a Nested Dictionary in Python

Adding items to a nested dictionary is straightforward. You can either add a new key-value pair to an existing nested dictionary or create a new nested dictionary altogether.

Let's add a new student to Grade 10:

school["Grade 10"]["Diana"] = {
    "age": 15,
    "subjects": ["Math", "Computer Science", "Literature"]
}

print(school["Grade 10"])

Output:

{
    'Charlie': {'age': 16, 'subjects': ['Physics', 'Chemistry', 'Biology']},
    'Diana': {'age': 15, 'subjects': ['Math', 'Computer Science', 'Literature']}
}

We can also add a new grade level:

school["Grade 11"] = {
    "Eve": {
        "age": 17,
        "subjects": ["Economics", "Psychology", "French"]
    }
}

print(school.keys())

Output:

dict_keys(['Grade 9', 'Grade 10', 'Grade 11'])

Accessing Items of a Nested Dictionary in Python

To access items in a nested dictionary, we use multiple square brackets, each representing a level of nesting. Let's retrieve some information from our school dictionary:

# Getting Alice's age
alice_age = school["Grade 9"]["Alice"]["age"]
print(f"Alice's age: {alice_age}")

# Getting Charlie's subjects
charlie_subjects = school["Grade 10"]["Charlie"]["subjects"]
print(f"Charlie's subjects: {charlie_subjects}")

Output:

Alice's age: 14
Charlie's subjects: ['Physics', 'Chemistry', 'Biology']

Remember, if you're not sure about the structure of your nested dictionary, you can always use the get() method to avoid KeyError exceptions:

# Trying to get a non-existent student
frank_age = school.get("Grade 9", {}).get("Frank", {}).get("age", "Not found")
print(f"Frank's age: {frank_age}")

Output:

Frank's age: Not found

Deleting a Dictionary from a Nested Dictionary

To remove a nested dictionary, we use the del keyword. Let's remove Bob from Grade 9:

del school["Grade 9"]["Bob"]
print(school["Grade 9"])

Output:

{'Alice': {'age': 14, 'subjects': ['Math', 'Science', 'English']}}

Be careful when deleting items from nested dictionaries. Always ensure that the keys exist to avoid KeyError exceptions.

Iterating Through a Nested Dictionary in Python

Iterating through a nested dictionary requires nested loops. Let's print out all the information in our school dictionary:

for grade, students in school.items():
    print(f"\n{grade}:")
    for student, info in students.items():
        print(f"  {student}:")
        for key, value in info.items():
            print(f"    {key}: {value}")

Output:

Grade 9:
  Alice:
    age: 14
    subjects: ['Math', 'Science', 'English']

Grade 10:
  Charlie:
    age: 16
    subjects: ['Physics', 'Chemistry', 'Biology']
  Diana:
    age: 15
    subjects: ['Math', 'Computer Science', 'Literature']

Grade 11:
  Eve:
    age: 17
    subjects: ['Economics', 'Psychology', 'French']

This nested loop structure allows us to access and print all levels of our nested dictionary.

Methods for Working with Nested Dictionaries

Here's a table of useful methods for working with nested dictionaries:

Method Description
dict.items() Returns a view object containing key-value pairs of the dictionary
dict.keys() Returns a view object containing keys of the dictionary
dict.values() Returns a view object containing values of the dictionary
dict.get(key, default) Returns the value for the specified key if it exists, otherwise returns the default value
dict.update(other_dict) Updates the dictionary with elements from another dictionary or iterable of key-value pairs
dict.pop(key, default) Removes and returns the value for the specified key. If the key doesn't exist, returns the default value

Remember, these methods can be applied at any level of a nested dictionary.

And there you have it, my dear students! We've explored the ins and outs of nested dictionaries in Python. From creating and adding items to accessing, deleting, and iterating through them, you now have the tools to work with these complex data structures.

As with any programming concept, practice is key. Try creating your own nested dictionaries, perhaps a digital library catalog or a recipe book. The more you play with these structures, the more comfortable you'll become.

Remember, in the world of programming, mistakes are just opportunities to learn. So don't be afraid to experiment and make errors - that's how we all grow as coders. Keep coding, keep learning, and most importantly, have fun with Python!

Credits: Image by storyset