1

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.

rose
  • 61
  • 4

1 Answers1

3

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.

Jay
  • 2,431
  • 1
  • 10
  • 21
  • thank you so much this is exactly what I am looking for I love you Jay – rose Dec 12 '22 at 07:58
  • hey I am trying to put a try-except block for a KeyError, how do I do it with dict comprehension? Tried a def function still could not do it.. Thanks!!! – rose Dec 23 '22 at 10:10
  • You cannot handle exceptions in the dict comprehension, you can either convert the dict comprehension into a for loop and then handle the exceptions there. Are you getting KeyError while doing `d2[v]`? You can replace it with `d2.get(v, [])` instead which return an empty list in case a `v` is not present in `d2`. – Jay Dec 23 '22 at 11:28
  • I made it like this and I think it worked:` d3= dict() for k1, v1 in d1.items(): try: d3[k1] = {} for v in v1: d3[k1][v] = d2[v] except KeyError as e: print(e) – rose Dec 24 '22 at 12:03
  • also thanks for answering!! do you have social media? – rose Dec 24 '22 at 12:03