0

I have a dictionary in python which is like below.

{'abc': [1,2,3], 'def': [2,3,4], 'gh': [3,4]}

I want to convert it to another dictionary like this:

{
1: 'abc',
2: 'abc, def',
3: 'abc, def, gh',
4: 'def, gh'
}

I wrote the following code, but got an error. How do I concatenate the values in dictionary? The order doesn't matter. thanks

old_dict=dict({'abc': [1,2,3], 'def': [2,3,4], 'gh': [3,4]})

new_dict1=dict()
for k, vlist in old_dict.items():
    for v in vlist:
        new_dict1[v]=new_dict1[v] + ", " + k

Traceback (most recent call last):
  File "<console>", line 3, in <module>
KeyError: 1
teapot
  • 77
  • 5

0 Answers0