piton

How to use Python dictionary of dictionaries

How to use Python dictionary of dictionaries
In most of the programming languages, an associative array is used to store data using key-value pairs. Dictionaries are used in Python to do the same task. The curly brackets () are used to declare any dictionary variable. The dictionary contains a unique key value as an index and each key represents a particular value. The third brackets ([]) are to read the value of any particular key.  Another data type exists in Python to store multiple data which is called List. The list works like a numeric array and its index starts from 0 and maintains order. But the key values of the dictionary contain different types of values that don't need to maintain any order. When one or more dictionaries are declared inside another dictionary then it is called a nested dictionary or dictionaries of the dictionary. How you can declare nested dictionaries and access data from them are described in this article by using different examples.

Example-1: Declare nested dictionary

A dictionary variable can store another dictionary in nested dictionary. The following example shows how nested dictionary can be declared and accessed using python. Here, 'courses' is a nested dictionary that contains other dictionary of three elements in each key. Next, for loop is used to read the value of each key of the nested dictionary.

# Create a nested dictionary
courses= 'bash': 'classes': 10, 'hours': 2, 'fee': 500,
'PHP': 'classes': 30, 'hours': 2, 'fee': 1500,
'Angular': 'classes': 10, 'hours': 2, 'fee': 1000
 
# Print the keys and values of the dictionary
for course in courses:
print('\nCourse Name:',course)
print('Total classes:',courses[course]['classes'])
print('Hours:',courses[course]['hours'])
print('Fee: $',courses[course]['fee'])

Output:

Run the script. The following output will appear after running the script.

Example-2: Insert data using specific key in a nested dictionary

A new data can be inserted or existing data can be modified in the dictionary by defining specific key of the dictionary. How you can insert new values in a nested dictionary by using key values are shown in this example. Here, 'products' is nested dictionary of three elements that contains another dictionary. A new key is defined for this dictionary to insert new elements. Next, three values are assigned using three key values and printed the dictionary using for loop.

# Create a nested dictionary
products = 't121': 'name': '42" Sony TV', 'brand': 'Sony', 'price':600,
'c702': 'name': 'Camera 8989', 'brand': 'Cannon', 'price':400,
'm432': 'name': 'Samsung Galaxy j10', 'brand': 'Samsung', 'price':200
# Define key for new dictionary entry
products['m123'] =
# Add values for new entry
products['m123']['name'] = 'iPhone 10'
products['m123']['brand'] = 'Apple'
products['m123']['price'] = 800
# Print the keys and values of the dictionary after insertion
for pro in products:
print('\nName:',products[pro]['name'])
print('Brand:',products[pro]['brand'])
print('Price:$',products[pro]['price'])

Output:

Run the script. The following output will appear after running the script.

Example-3: Insert a dictionary into the nested dictionary

This example shows how a new dictionary can be inserted as a new element for a nested dictionary. Here, a new dictionary is assigned as a value in a new key for 'products' dictionary.

# Create a nested dictionary
products = 't121': 'name': '42" Sony TV', 'brand': 'Sony', 'price':600,
'c702': 'name': 'Camera 8989', 'brand': 'Cannon', 'price':400
# Add new dictionary
products['f326'] = 'name': 'Fridge', 'brand': 'LG', 'price': 700
# Print the keys and values of the dictionary after insertion
for pro in products:
print('Name:',products[pro]['name'],', '
'Brand:',products[pro]['brand'], ', '
'Price:$',products[pro]['price'])

Output:

Run the script. The following output will appear after running the script.

Example-4: Delete data based on key from nested dictionary

This example shows how you can delete a value of a nested dictionary based on a particular key. The value of 'name' key of the second element of 'products' dictionary is removed here. Next, the dictionary values are printed based on keys.

# Create a nested dictionary
products = 't121': 'name': '42" Sony TV', 'brand': 'Sony', 'price':600,
'c702': 'name': 'Camera 8989', 'brand': 'Cannon', 'price':400,
'a512': 'name': 'AC', 'brand': 'General', 'price':650
# Delete data from the nested dictionary
del products['c702']['name']
print(products['t121'])
print(products['c702'])
print(products['a512'])

Output:

Run the script. The following output will appear after running the script. No value for 'name' key is printed for the second element.

Example-5: Delete a dictionary from a nested dictionary

This example shows the way to delete an internal dictionary entry from a nested dictionary in one statement. In nested dictionary, each key contains another dictionary. The third key of the nested dictionary is used in 'del' command to delete the internal dictionary that is assigned with that key. After delete, the nested dictionary is printed using for loop.

# Create a nested dictionary
products = 't121': 'name': '42" Sony TV', 'brand': 'Sony', 'price':600,
'c702': 'name': 'Camera 8989', 'brand': 'Cannon', 'price':400,
'a512': 'name': 'AC', 'brand': 'General', 'price':650
# Delete a dictionary from the nested dictionary
del products['a512']
# Print the keys and values of the dictionary after delete
for pro in products:
print('Name:',products[pro]['name'],', '
'Brand:',products[pro]['brand'], ', '
'Price:$',products[pro]['price'])

Output:

Run the script. The following output will appear after running the script.

Example-6: Remove the last inserted data from a nested dictionary

popitem() method is used to delete the last entry of a dictionary. The last entry of 'products' dictionary is deleted in this example by using popitem().

# Create a nested dictionary
products = 't121': 'name': '42" Sony TV', 'brand': 'Sony', 'price':600,
'c702': 'name': 'Camera 8989', 'brand': 'Cannon', 'price':400
# Delete the last dictionary entry
products.popitem()
 
# Print the keys and values of the dictionary after delete
for pro in products:
print('Name:',products[pro]['name'],', '
'Brand:',products[pro]['brand'], ', '
'Price:$',products[pro]['price'])

Output:

Run the script. The following output will appear after running the script.

Example-7: Access nested dictionaries using get() method

The values of all nested dictionaries are printed by using loop or keys in the above examples. get() method can be used in python to read the values of any dictionary. How the values of the nested dictionary can be printed by using get() method is shown in this example.

# Create a nested dictionary
products = 't121': 'name': '42" Sony TV', 'brand': 'Sony', 'price':600,
'c702': 'name': 'Camera 8989', 'brand': 'Cannon', 'price':400
 
# Print the keys and values of the dictionary after delete
for pro in products:
print('Name:',products[pro].get('name'))
print('Brand',products[pro].get('brand'))

Output:

Run the script. The following output will appear after running the script.

Conclusion

The different uses of the nested dictionary are shown in this article by using simple examples to help the python users to work with nested dictionaries.

Linux'ta FPS Nasıl Arttırılır?
FPS'nin kısaltması Saniyedeki Kare Sayısı. FPS'nin görevi, video oynatma veya oyun performanslarındaki kare hızını ölçmektir. Basit bir deyişle, her s...
En İyi Oculus Uygulama Laboratuvarı Oyunları
Oculus başlık sahibiyseniz, yandan yükleme hakkında bilgi sahibi olmalısınız. Sideloading, kulaklığınıza mağaza dışı içerik yükleme işlemidir. SideQue...
Ubuntu'da Oynanacak En İyi 10 Oyun
Windows platformu, günümüzde doğal olarak Windows'u desteklemek için geliştirilen oyunların büyük bir yüzdesi nedeniyle oyun oynamak için hakim platfo...