Python Forum

Full Version: Combining Dictionaries w/o overwriting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am trying to combine dictionaries into a single dictionary while retaining previous values.

I have provided an example code below. Ideally, I am trying to accomplish the following:

dict3 = {"dict1" = {"North America" : "United States" , "Europe" : "France" , "Asia" : "China" }, "dict2" = {"North America" : "Canada" , "Europe" : "Spain" , "Asia" : "Japan"}}

dict1 = {"North America" : "United States" , "Europe" : "France" , "Asia" : "China"}
dict2 = {"North America" : "Canada" , "Europe" : "Spain" , "Asia" : "Japan"}
dict3 = {}
dict3.update(dict1)
print(dict3)
dict3.update(dict2)
print(dict3)
I would be looking to add many potential dictionaries to the 'dict3' variable and all of the dictionaries could have "North America" as a key for example. Any feedback would be greatly appreciated!
How do you want the dictionaries to combine when they have different information for the same key? Can you give an example of what the final dictionary should look like? Your example line above the code doesn't make sense to me.

You either have to keep track of separate dictionaries (perhaps contained in a list or a tuple), or you have to figure out what to do with conflicting keys.

list_of_dicts = [dict1, dict2]
Keeps all the information, it's just not a third dict.
Sorry I meant to type : instead of the = sign.

So I want to dict3 to be the same as the targetdict. So effectively print(dict3) would be the same result as print(targetdict)

dict1 = {"North America" : "United States" , "Europe" : "France" , "Asia" : "China"}
dict2 = {"North America" : "Canada" , "Europe" : "Spain" , "Asia" : "Japan"}
dict3 = {}
targetdict = {"dict1" : {"North America" : "United States" , "Europe" : "France" , "Asia" : "China" }, "dict2" : {"North America" : "Canada" , "Europe" : "Spain" , "Asia" : "Japan"}}

dict3.update(dict1)
print(dict3)
dict3.update(dict2)
print(dict3)

If figured it out. The answer was actually very simple. Added below for reference-


dict1 = {"North America" : "United States" , "Europe" : "France" , "Asia" : "China"}
dict2 = {"North America" : "Canada" , "Europe" : "Spain" , "Asia" : "Japan"}
dict3 = {"North America" : "Mexico" , "Europe" : "Switzerland" , "Asia" : "Korea"}
finaldict = {}
targetdict = {"dict1" : {"North America" : "United States" , "Europe" : "France" , "Asia" : "China" }, "dict2" : {"North America" : "Canada" , "Europe" : "Spain" , "Asia" : "Japan"}}


finaldict['dict1'] = dict1
finaldict['dict2'] = dict2
finaldict['dict3'] = dict3

print(finaldict)
That looks like it works. What is your question about it?