Home > other >  How to merge lists value with shared key of two dictionaries?
How to merge lists value with shared key of two dictionaries?

Time:02-21

e.g.

d1 = {'a':[1, 2, 3], 'b': [1, 2, 3]}
d2 = {'a':[4, 5, 6], 'b': [3, 4, 5]}

The output should be like this:

{'a':[1, 2, 3, 4, 5, 6], 'b': [1, 2, 3, 4, 5]}

If the value repeats itself, it should be recorded only once.

CodePudding user response:

Assuming both dictionaries have the same keys and all keys are present in both dictionaries.

One way to achieve could be:

d1 = {'a':[1, 2, 3], 'b': [1, 2, 3]}
d2 = {'a':[4, 5, 6], 'b': [3, 4, 5]}

# make a list of both dictionaries
ds = [d1, d2]

# d will be the resultant dictionary
d = {}

for k in d1.keys():
    d[k] = [d[k] for d in ds]
    d[k] = list(set([item for sublist in d[k] for item in sublist]))

print(d)

Output

{'a': [1, 2, 3, 4, 5, 6], 'b': [1, 2, 3, 4, 5]}
  • Related