Home > Net >  Merge two python dictionaries on the same key and value
Merge two python dictionaries on the same key and value

Time:12-12

For example I have two dictionaries d1 and d2

d1 = {'a': ['b','c'], 'd': ['e', 'f']}
d2 = {'b':[1, 2], 'c': [3, 4], 'd': [5, 6], 'e': [7, 8], 'f': [9, 10]}

I expect a new dictionary d3 that looks like

d3 = {'a':{'b':[1, 2], 'c': [3, 4]}, 'd': {'e': [7, 8], 'f': [9, 10]}}

I have tried all kinds of looping but it does not work.

CodePudding user response:

You can use dict comprehension -

d1 = {'a': ['b','c'], 'd': ['e', 'f']}
d2 = {'b':[1, 2], 'c': [3, 4], 'd': [5, 6], 'e': [7, 8], 'f': [9, 10]}
d3 = {k1:{v:d2[v] for v in v1} for k1, v1 in d1.items()}
print(d3)

Output:

{'a': {'b': [1, 2], 'c': [3, 4]}, 'd': {'e': [7, 8], 'f': [9, 10]}}

Here, for every key(k1) in d1, we are creating an entry in d3 and the corresponding value is another dict, where key is values from first dict and corresponding value in d2 for the key.

  • Related