Reputation: 895
I have two nested dictionaries I am looking to combine. The keys on the outermost dictionaries are the same (A,B,C in this instance), but they differ on the inner-dictionaries.
dict1 = {'A': {'red': 4, 'yellow': 2, 'blue': 5}, 'B': {'orange': 1, 'purple': 2, 'green': 2}, 'C': {'black': 1, 'purple': 2, 'red': 2}}
dict2 = {'A': {'white': 1}, 'B': {'white': 2}, 'C': {'white': 3}}
What I want to do is create a new dictionary by adding the 'white' dictionary entry in dict2 to the corresponding entry in dict1 (based on their shared outer-keys). Ultimately, what I want to end up with is this:
finaldict = {'A': {'red': 4, 'yellow': 2, 'blue': 5, "white": 1}, 'B': {'orange': 1, 'purple': 2, 'green': 2, "white": 2}, 'C': {'black': 1, 'purple': 2, 'red': 2, "white": 3}}
Note: The order in which 'white' appears within each dictionary isn't a problem.
I have tried using the defaultdict
function from collections
but so far have only been able to group the two dictionaries at the outer-level
finaldict = defaultdict(list)
for d in (dict1, dict2):
for key, value in d.items():
data[key].append(value)
Upvotes: 0
Views: 35
Reputation: 17884
You can use the following dictcomp:
{key: {**dict1[key], **dict2[key]} for key in dict1.keys() | dict2.keys()}
Output:
{'A': {'red': 4, 'yellow': 2, 'blue': 5, 'white': 1},
'B': {'orange': 1, 'purple': 2, 'green': 2, 'white': 2},
'C': {'black': 1, 'purple': 2, 'red': 2, 'white': 3}}
Upvotes: 0
Reputation: 82785
Use dict.update
Ex:
dict1 = {'A': {'red': 4, 'yellow': 2, 'blue': 5}, 'B': {'orange': 1, 'purple': 2, 'green': 2}, 'C': {'black': 1, 'purple': 2, 'red': 2}}
dict2 = {'A': {'white': 1}, 'B': {'white': 2}, 'C': {'white': 3}}
for k, v in dict1.items():
key = dict2.get(k)
if key:
v.update(key)
print(dict1)
Output:
{'A': {'blue': 5, 'red': 4, 'white': 1, 'yellow': 2},
'B': {'green': 2, 'orange': 1, 'purple': 2, 'white': 2},
'C': {'black': 1, 'purple': 2, 'red': 2, 'white': 3}}
OR if you need a separate dict
result = {}
for k, v in dict1.items():
key = dict2.get(k, {})
result.setdefault(k, {}).update({**v, **key})
Upvotes: 1