0

I have a dictionary with keys and values as lists. something like:

d = {1:[0,1,2,3,4], 2:[1,3]}

I was on the lookout for swapping key value pairs. The output I am trying to get is:

o = {0:[1], 1:[1,2], 2:[1], 3:[1,2], 4:[1]}

Was wondering if there is a way to achieve this in the most efficient way

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Number Logic
  • 852
  • 1
  • 9
  • 19

1 Answers1

2

Use defaultdict:

In [30]: d = {1:[0,1,2,3,4], 2:[1,3]}

In [31]: from collections import defaultdict

In [32]: out = defaultdict(list)

In [33]: for k, v in d.items():
    ...:     for vv in v:
    ...:         out[vv].append(k)
    ...:

In [34]: dict(out)
Out[34]: {0: [1], 1: [1, 2], 2: [1], 3: [1, 2], 4: [1]}
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22