Home Python How to use Python Dictionary of Dictionaries

How to use Python Dictionary of Dictionaries

An associative array stores data using key-value pairs in most computer languages. In Python, dictionaries are utilized to accomplish the same goal. Any dictionary variable is declared using curly brackets { }. Each key represents a specific value, and the dictionary has a unique key value as an index.

The value of any key is read using the third brackets [ ]. In Python, another data type called list may be used to store several items. The list functions similarly to a numeric array, with an index that starts at 0 and preserves order. However, the dictionary’s key values comprise a variety of values that do not need to be in any particular order.

dic_example = {'key_1' : 'val_1', 'key_2': 'val_2'}

In the example above, the dictionary comprises a key: value pair enclosed within curly brackets {}

In Python, what is a nested dictionary?

A nested dictionary or dictionary of the dictionary is created when one or more dictionaries are specified inside another dictionary. It combines several dictionaries into a single dictionary.

nested_dict = { 'dictA': {'key_1': 'value_1'},  'dictB': {'key_2': 'value_2'}}

The nested_dict is a nested dictionary with the dictA and dictB dictionaries. Both dictionaries have their key and value.

Creating a Nested Dictionary in Python

We’re going to make a people dictionary within a dictionary. The first example shows how to make a nested dictionary.

students_dic = {1:{'name': 'ken', 'age': '9', 'sex': 'Male'},
                2:{'name': 'Joy', 'age': '12', 'sex': 'Female'},
                3:{'name': 'Bright', 'age': '34', 'sex': 'Male'}
               }

print(students_dic)

When we run the program mentioned above, we get the following results:

Creating a Nested Dictionary in Python
Creating a Nested Dictionary in Python

students_dic is a nested dictionary in the above application. Students are assigned to internal dictionaries 1, 2, and 3. All dictionaries have the variables names, ages, and genders with differing values. Finally, the students_dic’s results are printed.

Accessing elements in a Nested Dictionary

In Python, we utilize the indexing [] syntax to access elements of a hierarchical dictionary.

# Use the [] syntax to access the items
students_dic = {1: {'name': 'ken', 'age': '9', 'sex': 'Male'},
          2: {'name': 'Joy', 'age': '12', 'sex': 'Female'},
          3: {'name': 'Bright', 'age': '34', 'sex': 'Male'}

}

print(students_dic[1]['name'])
print(students_dic[2]['age'])
print(students_dic[3]['sex'])

When we run the program as mentioned earlier, we get the following results:

Accessing elements in a Nested Dictionary
Accessing elements in a Nested Dictionary

In the preceding program, we print the key name value using, i.e., students_dic[1][‘name’] from internal dictionary 1. We also print the age and sex values one by one of the subsequent students in the dictionary.

Adding an element to a Nested Dictionary

# In a nested dictionary, how do you alter or add elements?

students_dic = {1: {'name': 'ken', 'age': '9', 'sex': 'Male'},
          2: {'name': 'Joy', 'age': '12', 'sex': 'Female'},
          3: {'name': 'Bright', 'age': '34', 'sex': 'Male'}

}

students_dic[4] = {}

students_dic[4]['Catun'] = 'Luna'
students_dic[4]['age'] = '16'
students_dic[4]['sex'] = 'Male'
students_dic[4]['married'] = 'No'

print(students_dic[4])

When we run the program mentioned above, we get the following results:

Adding an element to a Nested Dictionary
Adding an element to a Nested Dictionary

We build an empty dictionary four inside the dictionary students_dic in the above application.

The key:value pair students_dic[4][‘Name’] = ‘Catun’ is then added to the dictionary 4.

We repeat this process for each critical age, sex, and married status. When we print the students_dic[4], we obtain dictionary four key: value pairs.

Example: adding another dictionary to the nested dictionary

students_dic = {1: {'name': 'ken', 'age': '9', 'sex': 'Male'},
          2: {'name': 'Joy', 'age': '12', 'sex': 'Female'},
          3: {'name': 'Bright', 'age': '34', 'sex': 'Male'},
          4: {'name': 'Catun', 'age': '16', 'sex': 'Male'}

}

students_dic[5] = {'name': 'Mam', 'age': '38', 'sex': 'Female', 'married': 'Yes'}
print(students_dic[5])

When we run the program mentioned above, we get the following results:

adding another dictionary to the nested dictionary
adding another dictionary to the nested dictionary

We allocate a dictionary literal to students_dic[5] in the above application. The literal has the keys name, age, and sex, as well as their values. Then we print students_dic[5] to see if dictionary four has been added to the nested dictionary students_dic.

Remove items from a Nested Dictionary

To delete elements from a nested dictionary in Python, use the ” del ” statement.

# How do you delete elements from a nested dictionary

students_dic = {1: {'name': 'ken', 'age': '9', 'sex': 'Male'},
          2: {'name': 'Joy', 'age': '12', 'sex': 'Female'},
          3: {'name': 'Bright', 'age': '34', 'sex': 'Male', 'married': 'No'},
          4: {'name': 'Catun', 'age': '16', 'sex': 'Male', 'married': 'Yes'}

}


del students_dic[3]['married']
del students_dic[4]['married']

print(students_dic[3])
print(students_dic[4])

When we run the program mentioned above, we get the following results:

Remove items from a Nested Dictionary
Remove items from a Nested Dictionary

We delete the key: value pairs of married from internal dictionaries 3 and 4 in the above application. The students_dic[3] and students_dic[4] are printed to confirm the modifications.

# How can I delete a nested dictionary's dictionary?
students_dic = {1: {'name': 'ken', 'age': '9', 'sex': 'Male'},
          2: {'name': 'Joy', 'age': '12', 'sex': 'Female'},
          3: {'name': 'Bright', 'age': '34', 'sex': 'Male', 'married': 'No'},
          4: {'name': 'Catun', 'age': '16', 'sex': 'Male', 'married': 'Yes'}

}


del students_dic[3]
del students_dic[4]

students_dic

When we run the program above, we get the following results:

deleting internal dictionaries
deleting internal dictionaries

Using del from the nested dictionary people, we delete both the internal dictionary 3 and 4 in the given application. The nested dictionary individuals are then printed to confirm modifications.

How can I delete a nested dictionary’s dictionary?

students_dic = {1: {'name': 'ken', 'age': '9', 'sex': 'Male'},
          2: {'name': 'Joy', 'age': '12', 'sex': 'Female'},
          3: {'name': 'Bright', 'age': '34', 'sex': 'Male', 'married': 'No'},
          4: {'name': 'Catun', 'age': '16', 'sex': 'Male', 'married': 'Yes'}
          }

del students_dic[3], students_dic[4]
print(students_dic)

When we run the program as mentioned earlier, we get the following results:

How can I delete a nested dictionary's dictionary?
How can I delete a nested dictionary’s dictionary?

Using del from the nested dictionary students_dic[, we delete the internal dictionaries 3 and 4 in the given application. The nested dictionary individuals are then printed to confirm modifications.

Iterating through a Nested Dictionary

We can cycle through each element in a nested dictionary using for loops.

# How do you iterate through a Nested dictionary?

students_dic  = {1: {'Name': 'ken', 'Age': '9', 'Sex': 'Male'},
          		 2: {'Name': 'Joy', 'Age': '12', 'Sex': 'Female'},
                 3: {'Name': 'Bright', 'Age': '34', 'Sex': 'Male'},
                 4: {'Name': 'Catun', 'Age': '16', 'Sex': 'Male'}}


for stu_id, stu_info in students_dic.items():
    print("\nStudent ID:", stu_id)
    
    for key in stu_info:
        print(key + ':', stu_info[key])

When we run the program above, we get the following results:

iterate through a Nested dictionary
iterate through a Nested dictionary

The first loop in the above software returns all the keys in the nested dictionary persons. It contains the stu_ids of each individual. These IDs are used to decode each student’s stu_info information.

The second loop goes over each student’s information. Then it returns all of the keys in each person’s vocabulary, such as name, age, and sex. We now print the key to the student’s information and its value.

This article uses many examples to demonstrate how to declare nested dictionaries and access data from them.

Example: Declare nested dictionary

In a nested dictionary, a dictionary variable can store another dictionary. The following example explains how to declare and access a nested dictionary in Python. ‘book_info’ is a nested dictionary in which each key contains another dictionary with three entries. Each key’s value of the nested dictionary is then read using a for a loop.

# Create a nested dictionary
book_info={ 'Introduction to Algorithms': {'chapters': 10, 'pages': 800, 'cost': 500},
          'JavaScript Fundamentals': {'chapters': 30, 'pages': 450, 'cost': 1500},
          'Object Oriented Programming': {'chapters': 10, 'pages': 210, 'cost': 1910}, ' Design Patterns in Python ': {'chapters': 10, 'pages':1200, 'cost': 1910}}
 
# Print the dictionary's keys and values.

for book in book_info:
  print('\nBook Name:',book_info)
  print('Total Chapters:', book_info [book]['chapters'])
  print('Pages:', book_info[book]['pages'])
  print('Cost: $', book_info[book]['cost'])

Execute the script. After running the script, the following output will show.

Create a nested dictionary
Create a nested dictionary

Example: inserting data using a certain key in a nested dictionary

New data can be inserted by establishing a specific dictionary key, or current data can be updated in the dictionary. This example shows how to use key values to insert new values into a nested dictionary. ‘Laptops’ is a three-element nested dictionary that contains another dictionary.

To add additional elements to this dictionary, a new key is defined. The dictionary is then written using a for loop after three values are assigned using three key values.

# Make a multi-level dictionary.
laptops = {'hp': {'name': ' Folio Elitebook 9470M', 'brand': 'HewlettPackard Laptop', 'price':30000},
            'lenovo': {'name': 'Camera 8989', 'brand': 'Lenovo Laptop', 'price':40000},
            'dell': {'name': 'Dell Inspiron', 'brand': 'Dell Laptop', 'price':200}}

# Define key for new dictionary entry
laptops['dell2'] = {}

# Add values for new entry
laptops ['dell2']['name'] = 'Dell Latitude'
laptops ['dell2']['brand'] = 'Dell Laptop'
laptops ['dell2']['price'] = 80000

# After insertion, print the dictionary's keys and values.

for lap in laptops:
  print('\nName:', laptops[lap]['name'])
  print('Brand:', laptops[lap]['brand'])
  print('Price:$', laptops[lap]['price'])

Execute the script. After running the script, the following output will show.

Handling multi-level dictionary
Handling multi-level dictionary

Example: Insert a dictionary inside the nested dictionary

This example demonstrates how a new dictionary can be added to a nested dictionary as a new element. Assigning a new dictionary as a value in the ” dictionary’s new key.

# Create a nested dictionary
laptops = {'hp': {'name': ' Folio Elitebook 9470M', 'brand': 'HewlettPackard Laptop', 'price':30000},
            'lenovo': {'name': 'Camera 8989', 'brand': 'Lenovo Laptop', 'price':40000},
            'dell': {'name': 'Dell Inspiron', 'brand': 'Dell Laptop', 'price':200}}

# Add new dictionary
laptops['ibm'] = {'name': 'IBM 1456', 'brand': 'IBM', 'price': 70000}

# After insertion, print the dictionary's keys and values. 
for lap in laptops:
  print('Name:', laptops[lap]['name'],', '
        'Brand:', laptops[lap]['brand'], ', '
        'Price:$', laptops[lap]['price'])

Execute the script. After running the script, the following output will show.

Insert a dictionary inside the nested dictionary

Insert a dictionary inside the nested dictionary

Example: Remove data from a nested dictionary depending on a key

This example demonstrates how to delete a nested dictionary value depending on a specific key. The value of the second element of the ‘laptops’ dictionary’s ‘name’ key is eliminated here. Following that, the dictionary values based on keys are printed.

# Create a nested dictionary
laptops = {'hp': {'name': ' Folio Elitebook 9470M', 'brand': 'HewlettPackard Laptop', 'price':30000},
            'lenovo': {'name': 'Camera 8989', 'brand': 'Lenovo Laptop', 'price':40000},
            'dell': {'name': 'Dell Inspiron', 'brand': 'Dell Laptop', 'price':200}}

# Delete data from the nested dictionary
del laptops['hp']['name']
print(laptops['dell'])
print(laptops['lenovo'])
print(laptops['hp'])

Execute the script. After running the script, the following output will show. No value for the ‘name’ key is shown for the second element.

Remove data from a nested dictionary depending on a key

Remove data from a nested dictionary depending on a key

Example: Delete a dictionary from a nested dictionary

This example demonstrates how to delete an internal dictionary entry from a nested dictionary with a single command. Each key in a nested dictionary contains another dictionary. The nested dictionary’s third key is used in the ‘del’ command to destroy the internal dictionary associated with that key. The nested dictionary is printed using a for loop after deletion.

# Create a nested dictionary
laptops = {'hp': {'name': ' Folio Elitebook 9470M', 'brand': 'HewlettPackard Laptop', 'price':30000},
            'lenovo': {'name': 'Camera 8989', 'brand': 'Lenovo Laptop', 'price':40000},
            'dell': {'name': 'Dell Inspiron', 'brand': 'Dell Laptop', 'price':200}}

# Delete a dictionary from the nested dictionary
del laptops['lenovo']

# After deleting the dictionary, print the keys and values.
for lap in laptops:
  print('Name:', laptops[lap]['name'],', '
        'Brand:', laptops[lap]['brand'], ', '
        'Price:$', laptops [lap]['price'])

Execute the script. After running the script, the following output will show.

Delete a dictionary from a nested dictionary

Delete a dictionary from a nested dictionary

Example: Remove the last inserted data from a nested dictionary

The popitem() method destroys the dictionary’s last element. In this example, popitem is used to delete the last entry of the ‘products’ dictionary ().

 # Create a nested dictionary
laptops = {'hp': {'name': ' Folio Elitebook 9470M', 'brand': 'HewlettPackard Laptop', 'price':30000},
            'lenovo': {'name': 'Camera 8989', 'brand': 'Lenovo Laptop', 'price':40000},
            'dell': {'name': 'Dell Inspiron', 'brand': 'Dell Laptop', 'price':200}}

# Delete the last dictionary entry
laptops.popitem()
 
# After deleting the dictionary, print the keys and values.
for lap in laptops:
  print('Name:', laptops[lap]['name'],', '
        'Brand:', laptops[lap]['brand'], ', '
        'Price:$', laptops[lap]['price'])

Execute the script. After running the script, the following output will show.

Remove the last inserted data from a nested dictionary
Remove the last inserted data from a nested dictionary

Example: Use the get() method to access nested dictionaries

In the examples above, the values of all nested dictionaries are printed using loops or keys. The get() function in Python can be used to read the contents of any dictionary. This example shows how to print the values of a nested dictionary using the get() method.

# Create a nested dictionary
laptops = {'hp': {'name': ' Folio Elitebook 9470M', 'brand': 'HewlettPackard Laptop', 'price':30000},
            'lenovo': {'name': 'Camera 8989', 'brand': 'Lenovo Laptop', 'price':40000},
            'dell': {'name': 'Dell Inspiron', 'brand': 'Dell Laptop', 'price':200}}
 
# After deleting the dictionary, print the keys and values.
for pro in laptops:
  print('Name:', laptops[lap].get('name'))
  print('Brand', laptops[lap].get('brand'))

Execute the script. After running the script, the following output will show.

Use the get() method to access nested dictionaries
Use the get() method to access nested dictionaries

Conclusion

We’ve learned about nested dictionaries in Python in this post. The key takeaways include: a nested dictionary is a set of dictionaries in no particular sequence. It is not feasible to slice a Nested Dictionary. Further, we can adjust the size of the nested dictionary as needed. In addition, it has both key and value, just like a dictionary. Also, note that the key is used to access the dictionary.

With the help of examples, you’ve seen how to create a nested dictionary, access elements, and alter them. Further, in this article, the various uses of the nested dictionary are demonstrated using simple examples to assist you in working with nested dictionaries.

You may also like

Leave a Comment