Skip to content Skip to sidebar Skip to footer

Adding A Dictionary Inside A Dictionary

I have a dictionary which looks like this: store = {} And I have a bunch of data in another dictionary that looks like this: items = {'hardware_items':23, 'fruit_items':5, 'fish_i

Solution 1:

Use the update method:

store.update(items)

This will add everything in items to store; beware though that if store already has existing keys with those names they will be overwritten.

Solution 2:

If store dict is empty you can use the copy() method :

store = items.copy()

You can use store = items but it works as a reference (then modifying store will modify items)

Else, you can use a for loop :

for keys in items:
    store[keys] = items[keys]

It will overwrite value if a key is already declared.

Solution 3:

The output you want would appear to be a copy of the "items" dictionary in "store". You can do this, basically, in two ways.

1. Simple copy

You can write

store = items

and the output will be what you asked for. Changing one of the two dictionaries, however, will also change the other.

2. Deep Copy

One of the ways to do a deep copy is:

store=copy.deepcopy(items)

In this case you will have two dictionaries with the same content, but they will be independent and you can edit them separately. Let me show an example:

import copy

store = {}
items = {"hardware_items":23, "fruit_items":5, "fish_items": 23}

#Printprint("Before operations")
print("ITEMS> "+str(items))
print("STORE> "+str(store))

store=copy.deepcopy(items)

#Printprint("After deep copy")
print("ITEMS> "+str(items))
print("STORE> "+str(store))


items["hardware_items"]=3#Printprint("let's modify the first key value")
print("ITEMS> "+str(items))
print("STORE> "+str(store))

Your output will be:

image example

Post a Comment for "Adding A Dictionary Inside A Dictionary"