Merge two python dictionaries on the same key and value

Question:

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.

Asked By: rose

||

Answers:

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.

Answered By: Jay
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.