Dict inside dict python

How to insert a dictionary in another dictionary in Python (How to merge two dictionaries)

Recently I was asked how to insert a hash in another hash in Perl and I thought I should look at this in Python as well.

There are two ways to «insert a dictionary in another dictionary».

Merge Dictionaries

One of them is to merge the two. All the keys of one of the dictionaries become also the keys of the other dictionary. Because how this works, it actually does not matter if the dictionary where the result will be is the same as one of the original ones, or if it is a third dictionary.

examples/python/merge_dictionaries.py

from __future__ import print_function team_a = < 'Foo' : 3, 'Bar' : 7, 'Baz' : 9, >team_b = < 'Moo' : 10, 'Boo' : 20, 'Foo' : 30, >print(team_a) # print(team_b) # team = dict(team_a.items() + team_b.items()) print(team) # team[«Foo»] = 100 print(team) # print(team_a) # print(team_b) #

As you can see there was a key that appeared in both dictionaries. For that particular key, in the resulting dictionary we got the value of the appropriate value form last (or right most) dictionary. (In our case that is team_b .)

We used the items method of the >dictionary object that returns a list of tuples. Each tuple holding one key-value pair from the dictionary. Then we take the two lists of tuples, add them together using the + operator. If we added the following code in the middle of our original script we could see that after the addition, we still have 6 tuples. We still have two tuples where the first element is ‘Foo’.

print(team_a.items()) # [('Baz', 9), ('Foo', 3), ('Bar', 7)] print(team_b.items()) # [('Foo', 30), ('Moo', 10), ('Boo', 20)] print(team_a.items() + team_b.items()) # [('Baz', 9), ('Foo', 3), ('Bar', 7), ('Foo', 30), ('Moo', 10), ('Boo', 20)]

Then we turn this list of tuples into a dictionary using the dict function. At this point the second value of the ‘Foo’ key overwrites the first one in the new dictionary.

So far this is ok. In order to see if these dictionaries are connected or not we can assign a new value to the ‘Foo’ key of the common dictionary: team[«Foo»] = 100 and then we check the content of the 3 dictionaries. The output shows that only the team dictionary has changed. The other two remained with the original values. This means the merging of the two dictionaries actually created a totally separate third dictionary.

Insert dictionary into another dictionary

The other way of insertion requires a new key in one of the dictionaries and the value will be the other dictionary.

Читайте также:  Html убрать перенос строки

examples/python/insert_dictionary.py

from __future__ import print_function team_a = < 'Foo' : 3, 'Bar' : 7, 'Baz' : 9, >team_b = < 'Moo' : 10, 'Boo' : 20, 'Foo' : 30, >print(team_a) # print(team_b) # team_a["b"] = team_b print(team_a) # <'Baz': 9, 'b': , 'Foo': 3, 'Bar': 7> team_b["Foo"] = 200 print(team_b) # print(team_a) # <'Baz': 9, 'b': , 'Foo': 3, 'Bar': 7>

In this case we assigned the team_b dictionary to a new key in the team_a dictionary. team_a[«b»] = team_b

In the result we can see that team_a has now 4 keys. The 3 it had earlier and the new key b , but the keys from team_b have not been merged. It became an internal dictionary. team_a became a (partially) 2-dimensional dictionary. If you wish. The key ‘Foo’ exists both in the external dictionary, and in the internal dictionary and they hold different values. They are not related at all.

Once that was done we used the same experiment as earlier and changed the content of ‘Foo’ key of the team_b dictionary using team_b[«Foo»] = 200 .

The resulting printout shows that both team_b , and the internal part of team have changed. That’s because in this case we assign a reference to the dictionary. So when we assigned team_b to team_a[«b»] we have not copied the content of team_b , we just connected the existing dictionary to another place where it can be accessed from.

Источник

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 ( ‘ \n Course Name:’ , course )
print ( ‘Total classes:’ , courses [ course ] [ ‘classes’ ] )
print ( ‘Hours:’ , courses [ course ] [ ‘hours’ ] )
print ( ‘Fee: $’ , courses [ course ] [ ‘fee’ ] )

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 ( ‘ \n Name:’ , products [ pro ] [ ‘name’ ] )
print ( ‘Brand:’ , products [ pro ] [ ‘brand’ ] )
print ( ‘Price:$’ , products [ pro ] [ ‘price’ ] )

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’ ] )

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’ ] )

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 [ ‘t121’ ]

# 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’ ] )

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’ ] )

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’ ) )

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.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью