Python Nested Dictionaries with Example | FACE Prep

Python Nested Dictionaries with Example | FACE Prep

Python Nested Dictionaries: A Complete Guide

Python nested dictionaries are an advanced feature of Python’s dictionary data type. Like standard dictionaries, nested dictionaries store data in key-value pairs but with the added complexity of having one or more dictionaries as values. This guide covers everything you need to know about nested dictionaries, their syntax, operations, and practical use cases.

What Are Nested Dictionaries?

A nested dictionary is an unordered collection of dictionaries within a dictionary. This structure allows hierarchical data storage and is particularly useful for representing real-world data like JSON objects.

Example Syntax:

nested_dict = {
    'dict1': {'key1': 'value1'},
    'dict2': {'key2': 'value2'}
}
In this example, nested_dict contains two dictionaries: dict1 and dict2. Each inner dictionary stores its own key-value pairs.

When to Use Nested Dictionaries

Nested dictionaries shine when dealing with complex data. For instance, imagine managing information about multiple employees. While a single dictionary works for one employee:
employee = {
    'name': 'John',
    'age': 37,
    'job': 'Software Developer',
    'city': 'Bangalore',
    'email': 'john@gmail.com'
}
Handling hundreds of employees calls for nested dictionaries:
employees = {
    101: {
        'name': 'John',
        'age': 37,
        'job': 'Software Developer'
    },
    102: {
        'name': 'Jane',
        'age': 29,
        'job': 'Data Analyst'
    }
}

Creating Nested Dictionaries

Syntax:

You can create a nested dictionary by nesting dictionaries within curly braces:
nested_dict = {
    'dict1': {'Color': 'Red', 'Shape': 'Square'},
    'dict2': {'Color': 'Pink', 'Shape': 'Round'}
}
print(nested_dict)
Output:
{'dict1': {'Color': 'Red', 'Shape': 'Square'}, 'dict2': {'Color': 'Pink', 'Shape': 'Round'}}

Basic Operations

Adding Key-Value Pairs:

To add new data to a nested dictionary:
nested_dict['dict3'] = {}
nested_dict['dict3']['Color'] = 'Blue'
nested_dict['dict3']['Shape'] = 'Rectangle'
print(nested_dict)
Output:
{
    'dict1': {'Color': 'Red', 'Shape': 'Square'},
    'dict2': {'Color': 'Pink', 'Shape': 'Round'},
    'dict3': {'Color': 'Blue', 'Shape': 'Rectangle'}
}

Adding Entire Dictionaries:

You can also add dictionaries directly:
nested_dict['dict4'] = {'Color': 'Green', 'Shape': 'Triangle'}

Accessing Values

Accessing values involves chaining keys:
nested_dict = {
    'dict1': {'Color': 'Red', 'Shape': 'Square'},
    'dict2': {'Color': 'Pink', 'Shape': 'Round'}
}
print(nested_dict['dict1']['Color'])  # Output: Red
print(nested_dict['dict2']['Shape'])  # Output: Round

Modifying Values

To modify a specific key-value pair:
nested_dict['dict1']['Color'] = 'Yellow'
print(nested_dict['dict1']['Color'])  # Output: Yellow

Deleting Elements

Deleting Specific Elements:

Use the del keyword to remove a key-value pair:
del nested_dict['dict1']['Color']
print(nested_dict)
Output:
{'dict1': {'Shape': 'Square'}, 'dict2': {'Color': 'Pink', 'Shape': 'Round'}}

Deleting Entire Dictionaries:

del nested_dict['dict1']
print(nested_dict)
Output:
{'dict2': {'Color': 'Pink', 'Shape': 'Round'}}

Practical Applications

Employee Management:

Nested dictionaries are ideal for storing structured data like employee records, student data, or inventory management.

JSON Parsing:

Since JSON structures often resemble nested dictionaries, Python’s dictionaries are the natural choice for JSON parsing and manipulation.

Tips and Best Practices

  1. Use Default Values: Avoid KeyErrors by using .get() or collections.defaultdict.
  2. Iterate Effectively: Use nested loops to traverse nested dictionaries.
  3. Structure Data Wisely: Plan the hierarchy for better readability and maintenance.

Nested dictionaries are a powerful tool for managing hierarchical and complex data. By mastering their usage, you can simplify operations on intricate datasets and write cleaner, more efficient Python code. Click here to know more our program!