Unlocking the Power of Nested Dictionaries in Python

The Basics of Nested Dictionaries

In Python, a nested dictionary is a collection of dictionaries within a single dictionary. This data structure allows you to store complex and hierarchical data in a flexible and efficient way. A nested dictionary is created by placing dictionaries inside another dictionary, with each inner dictionary having its own key-value pairs.

Building a Nested Dictionary

Let’s create a nested dictionary to store information about people. We’ll start with an empty dictionary called people and add internal dictionaries to it. Each internal dictionary will represent a person, with keys for their name, age, and sex.

people = {
    1: {'name': 'John', 'age': 25, 'ex': 'ale'},
    2: {'name': 'Jane', 'age': 30, 'ex': 'female'}
}

Accessing Elements in a Nested Dictionary

To access elements in a nested dictionary, you can use indexing syntax ([]) to navigate through the internal dictionaries. For example, to access the value of the 'name' key in the first internal dictionary, you would use people[1]['name'].

print(people[1]['name'])  # Output: John

Adding Elements to a Nested Dictionary

You can add new elements to a nested dictionary by assigning a new key-value pair to an internal dictionary. For example, let’s add a new person to the people dictionary.

people[3] = {'name': 'Luna', 'age': 28, 'ex': 'female'}

Deleting Elements from a Nested Dictionary

To delete elements from a nested dictionary, you can use the del statement. For example, let’s remove the 'married' key from the internal dictionaries.

del people[1]['married']  # Assuming 'arried' key exists
del people[2]['married']  # Assuming 'arried' key exists

Iterating Through a Nested Dictionary

You can iterate through a nested dictionary using for loops. The first loop iterates through the keys of the outer dictionary, while the second loop iterates through the keys of the internal dictionaries.

for p_id, p_info in people.items():
    for key, value in p_info.items():
        print(f"{p_id}: {key} = {value}")

Key Takeaways

  • A nested dictionary is an unordered collection of dictionaries.
  • Slicing a nested dictionary is not possible.
  • You can shrink or grow a nested dictionary as needed.
  • Like a regular dictionary, a nested dictionary has keys and values.
  • Dictionary elements are accessed using keys.

By mastering nested dictionaries, you can unlock new possibilities for storing and manipulating complex data in Python.

Leave a Reply