Dictionaries Inside Dictionaries

🏷️ Dictionaries / Nested Dictionaries


🌱 Context Introduction

As you start working with more complex data in Python, you'll quickly find that a simple flat dictionary isn't always enough. Imagine you need to store configuration details for multiple serversβ€”each server has its own IP address, operating system, and status. A dictionary inside a dictionary (often called a nested dictionary) lets you organize this data in a clean, hierarchical way. Think of it as a filing cabinet where each drawer (outer dictionary) contains folders (inner dictionaries) with specific details.


βš™οΈ What Is a Dictionary Inside a Dictionary?

A nested dictionary is simply a dictionary where the value for a key is another dictionary. This allows you to group related information together.

  • The outer dictionary holds the main categories or identifiers.
  • Each inner dictionary stores the specific attributes for that category.

Example structure: - Outer key: server1 β†’ Inner dictionary with keys: ip, os, status - Outer key: server2 β†’ Inner dictionary with keys: ip, os, status


πŸ› οΈ Creating a Nested Dictionary

You create a nested dictionary just like a regular dictionary, but the values are themselves dictionaries enclosed in curly braces {}.

Basic creation: - Start with outer curly braces {}. - For each outer key, assign an inner dictionary using {}. - Separate each key-value pair with a comma.

Example: - servers = { "web01": { "ip": "192.168.1.10", "os": "Ubuntu", "status": "active" }, "db01": { "ip": "192.168.1.20", "os": "CentOS", "status": "active" } }

This gives you a single variable servers that holds all server configurations.


πŸ“Š Accessing Values in a Nested Dictionary

To get a value from a nested dictionary, you chain the keys using square brackets [].

  • First bracket accesses the outer dictionary key.
  • Second bracket accesses the inner dictionary key.

Examples: - To get the IP of web01: servers["web01"]["ip"] returns "192.168.1.10" - To get the OS of db01: servers["db01"]["os"] returns "CentOS" - To get the status of web01: servers["web01"]["status"] returns "active"

If you try to access a key that doesn't exist, Python will raise a KeyError. Always double-check your key names.


πŸ•΅οΈ Adding and Updating Data

You can modify a nested dictionary just like a flat one, but you need to specify the full path to the value.

Adding a new inner dictionary: - servers["cache01"] = { "ip": "192.168.1.30", "os": "Debian", "status": "inactive" } - This adds a new outer key cache01 with its own inner dictionary.

Adding a new key to an existing inner dictionary: - servers["web01"]["uptime"] = "30 days" - This adds a new key uptime inside the web01 dictionary.

Updating an existing value: - servers["db01"]["status"] = "maintenance" - This changes the status of db01 from "active" to "maintenance".


πŸ”„ Looping Through a Nested Dictionary

When you loop through a nested dictionary, you typically use a for loop to go through the outer keys, then another loop to go through the inner keys.

Basic loop structure: - Use for outer_key, inner_dict in servers.items(): to get each outer key and its inner dictionary. - Inside that loop, use for inner_key, value in inner_dict.items(): to access each attribute.

Example output from looping: - web01 β†’ ip is 192.168.1.10 - web01 β†’ os is Ubuntu - web01 β†’ status is active - db01 β†’ ip is 192.168.1.20 - db01 β†’ os is CentOS - db01 β†’ status is active

This pattern is extremely useful when you need to process or display all data in a nested structure.


πŸ“‹ Comparison: Flat Dictionary vs. Nested Dictionary

Feature Flat Dictionary Nested Dictionary
Structure One level of key-value pairs Multiple levels (dictionary inside dictionary)
Example {"server1_ip": "10.0.0.1", "server1_os": "Ubuntu"} {"server1": {"ip": "10.0.0.1", "os": "Ubuntu"}}
Readability Becomes messy with many related attributes Groups related data logically
Access pattern Single key: data["server1_ip"] Chained keys: data["server1"]["ip"]
Use case Simple, unrelated data Complex, hierarchical data (e.g., configurations, inventories)

πŸ§ͺ Practical Example: Server Inventory

Imagine you are managing a small server inventory. A nested dictionary is perfect for this.

Data structure: - inventory = { "web01": { "ip": "10.0.0.1", "os": "Ubuntu 22.04", "ram_gb": 8, "cpu_cores": 4 }, "db01": { "ip": "10.0.0.2", "os": "CentOS 9", "ram_gb": 16, "cpu_cores": 8 }, "app01": { "ip": "10.0.0.3", "os": "Debian 12", "ram_gb": 4, "cpu_cores": 2 } }

To check the RAM of db01: - inventory["db01"]["ram_gb"] returns 16

To update the OS of app01: - inventory["app01"]["os"] = "Ubuntu 24.04"

To add a new server: - inventory["monitor01"] = { "ip": "10.0.0.4", "os": "Alpine", "ram_gb": 2, "cpu_cores": 1 }

This approach keeps your data organized and easy to maintain as your inventory grows.


βœ… Key Takeaways

  • A nested dictionary is a dictionary where values are themselves dictionaries.
  • Use chained square brackets to access, add, or update values.
  • Looping through a nested dictionary requires a nested for loop.
  • Nested dictionaries are ideal for representing hierarchical or grouped data like server configurations, user profiles, or application settings.
  • Always verify your key names to avoid KeyError exceptions.

πŸ“š Next Steps

Practice by creating your own nested dictionary for a small projectβ€”perhaps a list of network devices or a collection of application configurations. Try adding new entries, updating values, and looping through the entire structure to print a report. The more you work with nested dictionaries, the more natural they will feel.


A dictionary inside a dictionary lets you store related data in a structured, hierarchical way β€” like a folder of folders for your data.

πŸ“˜ Example 1: Creating a simple nested dictionary

This shows how to put one dictionary inside another dictionary as a value.

engineer = {
    "name": "Alice",
    "role": {
        "title": "Software Engineer",
        "level": "Senior"
    }
}
print(engineer)

πŸ“€ Output: {'name': 'Alice', 'role': {'title': 'Software Engineer', 'level': 'Senior'}}


πŸ“˜ Example 2: Accessing values inside a nested dictionary

This demonstrates how to reach a value stored in an inner dictionary using two keys.

engineer = {
    "name": "Bob",
    "team": {
        "name": "Platform",
        "size": 12
    }
}
team_name = engineer["team"]["name"]
print(team_name)

πŸ“€ Output: Platform


πŸ“˜ Example 3: Adding a new inner dictionary to an existing dictionary

This shows how to assign a new dictionary as a value to an existing key.

project = {
    "id": 101,
    "status": "active"
}
project["lead"] = {
    "name": "Carol",
    "email": "[email protected]"
}
print(project)

πŸ“€ Output: {'id': 101, 'status': 'active', 'lead': {'name': 'Carol', 'email': '[email protected]'}}


πŸ“˜ Example 4: Updating a value inside a nested dictionary

This shows how to modify a specific value that lives inside an inner dictionary.

server = {
    "hostname": "web-01",
    "config": {
        "port": 8080,
        "ssl": False
    }
}
server["config"]["ssl"] = True
print(server["config"])

πŸ“€ Output: {'port': 8080, 'ssl': True}


πŸ“˜ Example 5: Looping through a nested dictionary of engineers

This demonstrates how to iterate over a dictionary where each value is itself a dictionary.

team = {
    "E001": {"name": "Dave", "role": "Backend"},
    "E002": {"name": "Eve", "role": "Frontend"},
    "E003": {"name": "Frank", "role": "DevOps"}
}
for emp_id, details in team.items():
    print(emp_id, details["name"], details["role"])

πŸ“€ Output: E001 Dave Backend
πŸ“€ Output: E002 Eve Frontend
πŸ“€ Output: E003 Frank DevOps


πŸ“˜ Example 6: Checking if a key exists inside a nested dictionary

This shows how to safely test for a key in an inner dictionary before accessing it.

engineer = {
    "name": "Grace",
    "certifications": {
        "aws": True,
        "azure": False
    }
}
if "aws" in engineer["certifications"]:
    print("AWS certification status:", engineer["certifications"]["aws"])

πŸ“€ Output: AWS certification status: True


Quick Reference Table

Operation Syntax Example What It Does
Create nested dict outer = {"inner": {"key": value}} Puts a dict inside another dict
Access inner value outer["inner"]["key"] Gets value from the inner dict
Add inner dict outer["new"] = {"key": value} Inserts a new dict as a value
Update inner value outer["inner"]["key"] = new_value Changes a value inside the inner dict
Loop through nested for k, v in outer.items(): Iterates over each outer key and its inner dict

🌱 Context Introduction

As you start working with more complex data in Python, you'll quickly find that a simple flat dictionary isn't always enough. Imagine you need to store configuration details for multiple serversβ€”each server has its own IP address, operating system, and status. A dictionary inside a dictionary (often called a nested dictionary) lets you organize this data in a clean, hierarchical way. Think of it as a filing cabinet where each drawer (outer dictionary) contains folders (inner dictionaries) with specific details.


βš™οΈ What Is a Dictionary Inside a Dictionary?

A nested dictionary is simply a dictionary where the value for a key is another dictionary. This allows you to group related information together.

  • The outer dictionary holds the main categories or identifiers.
  • Each inner dictionary stores the specific attributes for that category.

Example structure: - Outer key: server1 β†’ Inner dictionary with keys: ip, os, status - Outer key: server2 β†’ Inner dictionary with keys: ip, os, status


πŸ› οΈ Creating a Nested Dictionary

You create a nested dictionary just like a regular dictionary, but the values are themselves dictionaries enclosed in curly braces {}.

Basic creation: - Start with outer curly braces {}. - For each outer key, assign an inner dictionary using {}. - Separate each key-value pair with a comma.

Example: - servers = { "web01": { "ip": "192.168.1.10", "os": "Ubuntu", "status": "active" }, "db01": { "ip": "192.168.1.20", "os": "CentOS", "status": "active" } }

This gives you a single variable servers that holds all server configurations.


πŸ“Š Accessing Values in a Nested Dictionary

To get a value from a nested dictionary, you chain the keys using square brackets [].

  • First bracket accesses the outer dictionary key.
  • Second bracket accesses the inner dictionary key.

Examples: - To get the IP of web01: servers["web01"]["ip"] returns "192.168.1.10" - To get the OS of db01: servers["db01"]["os"] returns "CentOS" - To get the status of web01: servers["web01"]["status"] returns "active"

If you try to access a key that doesn't exist, Python will raise a KeyError. Always double-check your key names.


πŸ•΅οΈ Adding and Updating Data

You can modify a nested dictionary just like a flat one, but you need to specify the full path to the value.

Adding a new inner dictionary: - servers["cache01"] = { "ip": "192.168.1.30", "os": "Debian", "status": "inactive" } - This adds a new outer key cache01 with its own inner dictionary.

Adding a new key to an existing inner dictionary: - servers["web01"]["uptime"] = "30 days" - This adds a new key uptime inside the web01 dictionary.

Updating an existing value: - servers["db01"]["status"] = "maintenance" - This changes the status of db01 from "active" to "maintenance".


πŸ”„ Looping Through a Nested Dictionary

When you loop through a nested dictionary, you typically use a for loop to go through the outer keys, then another loop to go through the inner keys.

Basic loop structure: - Use for outer_key, inner_dict in servers.items(): to get each outer key and its inner dictionary. - Inside that loop, use for inner_key, value in inner_dict.items(): to access each attribute.

Example output from looping: - web01 β†’ ip is 192.168.1.10 - web01 β†’ os is Ubuntu - web01 β†’ status is active - db01 β†’ ip is 192.168.1.20 - db01 β†’ os is CentOS - db01 β†’ status is active

This pattern is extremely useful when you need to process or display all data in a nested structure.


πŸ“‹ Comparison: Flat Dictionary vs. Nested Dictionary

Feature Flat Dictionary Nested Dictionary
Structure One level of key-value pairs Multiple levels (dictionary inside dictionary)
Example {"server1_ip": "10.0.0.1", "server1_os": "Ubuntu"} {"server1": {"ip": "10.0.0.1", "os": "Ubuntu"}}
Readability Becomes messy with many related attributes Groups related data logically
Access pattern Single key: data["server1_ip"] Chained keys: data["server1"]["ip"]
Use case Simple, unrelated data Complex, hierarchical data (e.g., configurations, inventories)

πŸ§ͺ Practical Example: Server Inventory

Imagine you are managing a small server inventory. A nested dictionary is perfect for this.

Data structure: - inventory = { "web01": { "ip": "10.0.0.1", "os": "Ubuntu 22.04", "ram_gb": 8, "cpu_cores": 4 }, "db01": { "ip": "10.0.0.2", "os": "CentOS 9", "ram_gb": 16, "cpu_cores": 8 }, "app01": { "ip": "10.0.0.3", "os": "Debian 12", "ram_gb": 4, "cpu_cores": 2 } }

To check the RAM of db01: - inventory["db01"]["ram_gb"] returns 16

To update the OS of app01: - inventory["app01"]["os"] = "Ubuntu 24.04"

To add a new server: - inventory["monitor01"] = { "ip": "10.0.0.4", "os": "Alpine", "ram_gb": 2, "cpu_cores": 1 }

This approach keeps your data organized and easy to maintain as your inventory grows.


βœ… Key Takeaways

  • A nested dictionary is a dictionary where values are themselves dictionaries.
  • Use chained square brackets to access, add, or update values.
  • Looping through a nested dictionary requires a nested for loop.
  • Nested dictionaries are ideal for representing hierarchical or grouped data like server configurations, user profiles, or application settings.
  • Always verify your key names to avoid KeyError exceptions.

πŸ“š Next Steps

Practice by creating your own nested dictionary for a small projectβ€”perhaps a list of network devices or a collection of application configurations. Try adding new entries, updating values, and looping through the entire structure to print a report. The more you work with nested dictionaries, the more natural they will feel.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

A dictionary inside a dictionary lets you store related data in a structured, hierarchical way β€” like a folder of folders for your data.

πŸ“˜ Example 1: Creating a simple nested dictionary

This shows how to put one dictionary inside another dictionary as a value.

engineer = {
    "name": "Alice",
    "role": {
        "title": "Software Engineer",
        "level": "Senior"
    }
}
print(engineer)

πŸ“€ Output: {'name': 'Alice', 'role': {'title': 'Software Engineer', 'level': 'Senior'}}


πŸ“˜ Example 2: Accessing values inside a nested dictionary

This demonstrates how to reach a value stored in an inner dictionary using two keys.

engineer = {
    "name": "Bob",
    "team": {
        "name": "Platform",
        "size": 12
    }
}
team_name = engineer["team"]["name"]
print(team_name)

πŸ“€ Output: Platform


πŸ“˜ Example 3: Adding a new inner dictionary to an existing dictionary

This shows how to assign a new dictionary as a value to an existing key.

project = {
    "id": 101,
    "status": "active"
}
project["lead"] = {
    "name": "Carol",
    "email": "[email protected]"
}
print(project)

πŸ“€ Output: {'id': 101, 'status': 'active', 'lead': {'name': 'Carol', 'email': '[email protected]'}}


πŸ“˜ Example 4: Updating a value inside a nested dictionary

This shows how to modify a specific value that lives inside an inner dictionary.

server = {
    "hostname": "web-01",
    "config": {
        "port": 8080,
        "ssl": False
    }
}
server["config"]["ssl"] = True
print(server["config"])

πŸ“€ Output: {'port': 8080, 'ssl': True}


πŸ“˜ Example 5: Looping through a nested dictionary of engineers

This demonstrates how to iterate over a dictionary where each value is itself a dictionary.

team = {
    "E001": {"name": "Dave", "role": "Backend"},
    "E002": {"name": "Eve", "role": "Frontend"},
    "E003": {"name": "Frank", "role": "DevOps"}
}
for emp_id, details in team.items():
    print(emp_id, details["name"], details["role"])

πŸ“€ Output: E001 Dave Backend
πŸ“€ Output: E002 Eve Frontend
πŸ“€ Output: E003 Frank DevOps


πŸ“˜ Example 6: Checking if a key exists inside a nested dictionary

This shows how to safely test for a key in an inner dictionary before accessing it.

engineer = {
    "name": "Grace",
    "certifications": {
        "aws": True,
        "azure": False
    }
}
if "aws" in engineer["certifications"]:
    print("AWS certification status:", engineer["certifications"]["aws"])

πŸ“€ Output: AWS certification status: True


Quick Reference Table

Operation Syntax Example What It Does
Create nested dict outer = {"inner": {"key": value}} Puts a dict inside another dict
Access inner value outer["inner"]["key"] Gets value from the inner dict
Add inner dict outer["new"] = {"key": value} Inserts a new dict as a value
Update inner value outer["inner"]["key"] = new_value Changes a value inside the inner dict
Loop through nested for k, v in outer.items(): Iterates over each outer key and its inner dict