Python – Nested Dictionaries

In Python, a nested dictionary is a dictionary where some of the values are themselves dictionaries. This allows you to create complex data structures, where you can store and access data in a hierarchical manner.

Here’s how you can work with nested dictionaries:


1. Creating a Nested Dictionary

A nested dictionary is created by using dictionaries as values within other dictionaries.

Example:

nested_dict = {
    'person1': {
        'name': 'Alice',
        'age': 25,
        'city': 'New York'
    },
    'person2': {
        'name': 'Bob',
        'age': 30,
        'city': 'Los Angeles'
    }
}

print(nested_dict)

Output:

{
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

2. Accessing Values in a Nested Dictionary

To access a value in a nested dictionary, you can use multiple keys, one for each level of the dictionary.

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Accessing the name of person1
print(nested_dict['person1']['name'])  # Output: Alice

# Accessing the city of person2
print(nested_dict['person2']['city'])  # Output: Los Angeles

3. Modifying Values in a Nested Dictionary

You can modify values within a nested dictionary by referencing the key-path to the item.

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Modifying the age of person1
nested_dict['person1']['age'] = 26

# Adding a new field for person2
nested_dict['person2']['country'] = 'USA'

print(nested_dict)

Output:

{
    'person1': {'name': 'Alice', 'age': 26, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles', 'country': 'USA'}
}

4. Adding a New Nested Dictionary

You can add new nested dictionaries by assigning a dictionary as the value to a new key.

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Adding a new person (person3)
nested_dict['person3'] = {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}

print(nested_dict)

Output:

{
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'},
    'person3': {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
}

5. Looping Through a Nested Dictionary

You can loop through a nested dictionary using nested loops or dictionary methods like .items().

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Looping through the outer dictionary (person)
for person, details in nested_dict.items():
    print(f"{person}:")
    
    # Looping through the inner dictionary (details)
    for key, value in details.items():
        print(f"  {key}: {value}")

Output:

person1:
  name: Alice
  age: 25
  city: New York
person2:
  name: Bob
  age: 30
  city: Los Angeles

6. Using get() with Nested Dictionaries

You can use the get() method to access values in a nested dictionary, which will return None (or a default value) if the key doesn’t exist.

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Using get() to access a value
print(nested_dict.get('person1', {}).get('name'))  # Output: Alice

# Using get() with a default value when the key doesn't exist
print(nested_dict.get('person3', {}).get('name', 'Unknown'))  # Output: Unknown

7. Deleting Items from a Nested Dictionary

You can delete items from a nested dictionary using the del statement or the pop() method.

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Deleting a field from person1
del nested_dict['person1']['age']

# Deleting an entire person
del nested_dict['person2']

print(nested_dict)

Output:

{
    'person1': {'name': 'Alice', 'city': 'New York'}
}

8. Checking for Keys in a Nested Dictionary

You can check if a key exists at any level in a nested dictionary using the in keyword.

Example:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
}

# Checking for a key in the outer dictionary
if 'person1' in nested_dict:
    print("person1 exists.")

# Checking for a key in the inner dictionary
if 'age' in nested_dict['person1']:
    print("Age exists for person1.")

Output:

person1 exists.
Age exists for person1.

Summary of Operations on Nested Dictionaries:

  • Accessing: Use multiple keys (e.g., nested_dict['person1']['name']).
  • Modifying: Modify values by referencing keys (nested_dict['person1']['age'] = 26).
  • Adding: Add new items using new keys (nested_dict['person3'] = {...}).
  • Looping: Use for loops with .items() to loop through keys and values.
  • Deleting: Use del or pop() to remove items.
  • Checking Keys: Use in to check for keys in outer and inner dictionaries.
  • Using get(): Safely access values with get() to avoid KeyError.
Leave a Reply 0

Your email address will not be published. Required fields are marked *