Nested Dictionaries Course with Python

Python Nested Dictionaries Course

Introduction to Nested Dictionaries

In Python, dictionaries are data structures that store key-value pairs. A nested dictionary is simply a dictionary that contains other dictionaries as its values. This allows you to create complex, hierarchical data structures.

Creating Nested Dictionaries

A nested dictionary is created using the standard dictionary syntax, but with dictionaries as values. Here’s a simple example: 

# Creating a nested dictionary
person = {
    "name": "Alice",
    "address": {
        "street": "123 Main St",
        "city": "Paris",
        "postal_code": "75001"
    },
    "contacts": {
        "email": "alice@example.com",
        "phone": "0123456789"
    }
}

Accessing Items in a Nested Dictionary

To access an item in a nested dictionary, you use the keys for each level of the structure. Here’s how to access specific items from the person dictionary: 

# Accessing the name
name = person["name"]
print(name)  # Output: Alice
# Accessing the address
address = person["address"]
print(address)  # Output: {'street': '123 Main St', 'city': 'Paris', 'postal_code': '75001'}
# Accessing the street
street = person["address"]["street"]
print(street)  # Output: 123 Main St
# Accessing the phone number
phone = person["contacts"]["phone"]
print(phone)  # Output: 0123456789

Looping Through Nested Dictionaries

You can use loops to iterate through the items in a nested dictionary. Here are some examples:

Loop Through Keys and Values

To loop through the keys and values of a nested dictionary, you can use for loops. Here’s an example: 

# Looping through the keys and values of the address
for key, value in person["address"].items():
    print(f"{key}: {value}")
# Output:
# street: 123 Main St
# city: Paris
# postal_code: 75001

Loop Through Nested Dictionaries

To loop through the nested dictionaries themselves, you can use nested loops: 

# Looping through nested dictionaries
for category, info in person.items():
    print(f"Category: {category}")
    if isinstance(info, dict):
        for key, value in info.items():
            print(f"  {key}: {value}")
    else:
        print(f"  {info}")
# Output:
# Category: name
#   Alice
# Category: address
#   street: 123 Main St
#   city: Paris
#   postal_code: 75001
# Category: contacts
#   email: alice@example.com
#   phone: 0123456789

Modifying Values in a Nested Dictionary

You can modify values in a nested dictionary similarly to how you modify values in a flat dictionary. Here’s how to update information in the person dictionary: 

# Modifying the street
person["address"]["street"] = "456 New St"
# Adding a new contact
person["contacts"]["mobile"] = "0987654321"
print(person)
# Output:
# {
#     'name': 'Alice',
#     'address': {
#         'street': '456 New St',
#         'city': 'Paris',
#         'postal_code': '75001'
#     },
#     'contacts': {
#         'email': 'alice@example.com',
#         'phone': '0123456789',
#         'mobile': '0987654321'
#     }
# }

Deleting Items from a Nested Dictionary

To delete items, use the del statement to remove specific keys: 

# Deleting the phone number
del person["contacts"]["phone"]
print(person)
# Output:
# {
#     'name': 'Alice',
#     'address': {
#         'street': '456 New St',
#         'city': 'Paris',
#         'postal_code': '75001'
#     },
#     'contacts': {
#         'email': 'alice@example.com',
#         'mobile': '0987654321'
#     }
# }

Conclusion

Nested dictionaries are powerful for organizing hierarchical data. By understanding how to create, access, modify, and loop through these structures, you can efficiently manage complex data in Python.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print