Python

Python Nested Dictionary Usage

Python’s application of nested dictionaries proves to be a powerful solution for data organization. Allowing dictionaries within dictionaries offers an efficient method to structure and store the information. This data structure supports the creation of complex, hierarchical models where each level corresponds to a key-value pair. Its usage is particularly advantageous in scenarios that require an organized data such as configurations, hierarchies, or multidimensional datasets. Python’s nested dictionaries make it a favored option for developers who aim to combine the complex data structures with efficient and easily understandable code.

Example 1: Basic Structure

Python’s nested dictionaries are a robust instrument to manage the complex data structures. In this example, we will delve into various scenarios to understand this powerful feature’s practical applications and benefits.

Let’s begin with a fundamental example to clarify our understanding of nested dictionaries in the following given example:

person = {
    "name": "Aizel",
    "age": 30,
    "contact": {
        "email": "[email protected]",
        "phone": "345-458-6995"
    }
}

 
We created the outer dictionary of a person. The outermost layer is a dictionary named “person” which serves as a container for organizing the information about an individual. The key-value pairs in this layer include “name” and “age” which provide the basic details about the person.

Then, we created the nested dictionary contact. This is created within the person dictionary, and there is a key-value pair where the key is “contact” and the value is another dictionary. This nested dictionary, labeled as “contact”, includes a more detailed information, specifically the person’s email and phone number. Within the “contact” dictionary are two key-value pairs which are “email” and “phone”. Each key is associated with a specific piece of contact information.

Example 2: Accessing the Nested Elements

Let’s now explore how accessing the elements within the nested dictionaries is essential. Using the previous example, let’s retrieve the person’s email address. Accessing the email address requires us to go through the key’s “contact” and “email” sequentially.

person = {
    "name": "Aizel",
    "age": 30,
    "contact": {
        "email": "[email protected]",
        "phone": "345-458-6995"
    }
}
email = person["contact"]["email"]
print("Email:", email)

 

This simple indexing simplifies the extraction of specific information from deeply nested dictionaries.

Example 3: Modifying the Nested Values

Nested dictionaries, being variable, allow us to update the values dynamically. Let’s modify a person’s phone number from the previous example. By referencing the keys like “contact” and “phone”, we can directly modify the corresponding values.

person = {
    "name": "Aizel",
    "age": 30,
    "contact": {
        "email": "[email protected]",
        "phone": "345-458-6995"
    }
}
person["contact"]["phone"] = "987-654-3210"
Contact= person["contact"]["phone"]
print("contact:", Contact)

 

This dynamic updating capability proves invaluable for scenarios where the data changes, ensuring that the dictionary remains current.

Example 4: Adding New Nested Key-Value Pairs

The expansion of nested dictionaries through the addition of new key-value pairs is effortless. Let’s include the person’s address again. Introducing a new key which is “address”, brings another dictionary that contains the street, city, and zip code details.

person = {
    "name": "Aizel",
    "age": 30,
    "contact": {
        "email": "[email protected]",
        "phone": "345-458-6995"
    }
}
person["contact"]["address"] = {
    "street": "123 Main St",
    "city": "Anytown",
    "zip": "56789"
}
Address = person["contact"]["address"]
print ("address:",Address)

 

This flexibility facilitates the expansion of data structures without making extensive modifications.

Example 5: Nested Dictionaries in a List

Now, consider a scenario where a list of people is represented, each represented by a nested dictionary. The “people” list has a total of two dictionaries, each representing an individual.

people = [
    {"name": "Hamid", "age": 30, "contact": {"email": "[email protected]", "phone": "123-456-7890"}},
    {"name": "Aizel", "age": 25, "contact": {"email": "[email protected]", "phone": "987-654-3210"}}
]
# Access Hamid's age
Hamid_age = people[0]["age"]
print("Hamid's Age:", Hamid_age)

# Access Aizel's email
aizel_email = people[1]["contact"]["email"]
print("Aizel's Email:", aizel_email)

 

We can observe from this example that the uniformity in the nested structure allows for consistent representation within the list.

Example 6: Iteration through Nested Dictionaries

To extract an information from multiple nested dictionaries, we use the loops. Let’s now iterate through the list of people by printing their names and email addresses. The “for” loop iterates through each dictionary in the “people” list as shown in the following given code:

people = [
    {"name": "Hamid", "age": 30, "contact": {"email": "[email protected]", "phone": "123-456-7890"}},
    {"name": "Aizel", "age": 25, "contact": {"email": "[email protected]", "phone": "987-654-3210"}}
]
for person in people:
    print("Name:", person["name"])
    print("Email:", person["contact"]["email"])

 

Accessing the values like “name” and “email” within the loop demonstrates the efficiency of nested dictionaries in handling the related data collections.

Example 7: Real-World Application for JSON-Like Data

Nested dictionaries have common applications in handling a JSON-like data. Consider a JSON response from an API that contains an information about books. The “books” key contains a list of dictionaries, each representing a book with attributes like title, author, and publication year.

book_data = {
    "books": [
        {"title": "The Power of Language", "author": "Van Rossum", "year": 2020},
        {"title": "Machine Learning for Beginners", "author": "Keeaunu Doe", "year": 2021}
    ]
}
# Accessthe title of Book 1
title_book1 = book_data["books"][0]["title"]
print("Title of Book 1:", title_book1)

# Access the author of Book 2
author_book2 = book_data["books"][1]["author"]
print("Author of Book 2:", author_book2)

 

This structure copies and shows the JSON data format that is prevalent in web development.

Example 8: Deeply Nested Structures

In complex scenarios, deeply nested structures may arise. Consider a scenario where a dictionary represents a company’s organizational structure.

organization = {
    "name": "TechCo",
    "departments": {
        "engineering": {
            "manager": "John Smith",
            "teams": {
                "frontend": ["Alice", "Bob"],
                "backend": ["Charlie", "David"]
            }
        },
        "marketing": {
            "manager": "Alice Johnson",
            "teams": {
                "campaigns": ["Eve", "Frank"],
                "analytics": ["Grace", "Harry"]
            }
        }
    }
}

 
This example showcases a more complex structure with the nested dictionaries representing the company, departments, teams, and team members.

Deeply nested structures excel at representing complex organizational hierarchies or project structures.

Example 9: Error Handling with Nested Dictionaries

Effective error handling becomes essential when data integrity is not guaranteed or when dealing with potentially missing or improperly formatted data. This example demonstrates how to implement the error handling when trying to access a key that might not exist in a nested dictionary.

person = {
    "name": "Aizel",
    "age": 30,
    "contact": {
        "email": "[email protected]",
        "phone": "345-458-6995"
    }
}

try:
    salary = person["salary"]
except KeyError:
    print("Salary information not found.")

 
The “try” block contains the code where an error might occur. In this case, we attempt to access the “salary” key in the “person” dictionary. If the key is present, the code within the “try” block is executed without any interruption. The “except” block specifies the type of error to catch which, in this case, is “KeyError”. Trying to access a key that isn’t in the dictionary results in a “KeyError”.

In the event that a “KeyError” is raised while the “try” block is being processed, the “except” block’s function will be executed in response. In a “KeyError”, the code within the “except” block is executed. In this example, a simple message is printed, i.e. “Salary information not found”.


This provides a clear indication to the developer or user that the expected key (“salary”) does not exist in the nested dictionary.

Example 10: Nesting Based on Conditions

Nesting dictionaries based on conditions is also achievable. Consider categorizing the people into different groups based on their age.

age_groups = {}
for person in people:
    age = person["age"]
    if age < 30:
        age_groups.setdefault("young", []).append(person)
    else:
        age_groups.setdefault("adult", []).append(person)
{
    "young": [
        {"name": "Aizel", "age": 25, "contact": {"email": "[email protected]", "phone": "987-654-3210"}}
    ],
    "adult": [
        {"name": "Hamid", "age": 30, "contact": {"email": "[email protected]", "phone": "123-456-7890"}}
    ]
}
# display the contents of the age_groups dictionary
for category, individuals in age_groups.items():
    print(f"People in the {category} category:")
    for person in individuals:
        print(f"  {person['name']} - Age: {person['age']}")

 

This example categorizes the individuals into age groups (“young” or “adult”) within the “age_groups” dictionary. The “setdefault” method ensures that the keys are created dynamically as needed.

Dynamic nesting based on conditions demonstrates the usage of nested dictionaries for diverse data structures.

Conclusion

In conclusion, these examples illuminate the versatility and practicality of Python nested dictionaries. Whether representing the hierarchical data structures, handling the JSON-like responses, or modeling the complex relationships, nested dictionaries provide a flexible and efficient solution. Their dynamic nature, combined with intuitive syntax, ranks Python as an ideal language for scenarios where data organization and manipulation are needed.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.