Reputation: 1
dictx1 = {}
dictx2 = {'C':['D','A'],'sXZ':['W','L']}
dictx3 = {'C':['3','4'],'sXZ':['3KL','E','S']}
I want to merge dictx2 and dictx3 to dictx1 and get the output as "{'C': ['D', 'A','3','4'], 'sXZ': ['W', '3KL', 'L', 'E','S']}"
I wrote below code
dictx1 = {}
dictx1 = dictx2.copy()
ds= [dictx1, dictx3]
for i in dictx2.keys():
dictx1[i] = list(lix[i][x] for x in range(len(lix[i]) for lix in ds)
Error: dictx1[i] = list(lix[i][x] for x in range(len(lix[i])) for lix in ds) NameError: name 'lix' is not defined
But it already there with the 'for lix in ds'. I can write the code as below to get the same answer. But I want to know what's wrong with the above one line for code
s=[]
for i in dictx2.keys():
for li in ds:
for x in range(len(li[i])):
s.append(li[i][x])
dictx1[i] = s
s = []
print (dictx1)
Upvotes: 0
Views: 71
Reputation: 43196
You can use a defaultdict
and add all lists in a loop:
from collections import defaultdict
dictx1 = defaultdict(list)
for dic in (dictx2, dictx3):
for key, value in dic.items():
dictx1[key].extend(value)
# result: defaultdict(<class 'list'>, {'C': ['D', 'A', '3', '4'],
# 'sXZ': ['W', 'L', '3KL', 'E', 'S']})
If you don't want a defaultdict
as the result, add dictx1 = dict(dictx1)
to turn it into a normal dict.
Upvotes: 0
Reputation: 4983
dictx2 = {'C':['D','A'],'sXZ':['W','L']}
dictx3 = {'C':['3','4'],'sXZ':['3KL','E','S']}
for k,v in dictx2.items():
res = dictx3.get(k, None)
if res == None:
dictx3.update({k:v})
else:
dictx3.update({k : v + res})
print(dictx3)
output
{'C': ['D', 'A', '3', '4'], 'sXZ': ['W', 'L', '3KL', 'E', 'S']}
Upvotes: 2