2

Similarly to this question and this question, I'd like to swap keys and values in a dictionary.

The difference is, my values are lists, not just single values.

Thus, I'd like to turn:

In [120]: swapdict = dict(foo=['a', 'b'], bar=['c', 'd'])

In [121]: swapdict
Out[121]: {'bar': ['c', 'd'], 'foo': ['a', 'b']}

into:

{'a': 'foo', 'b': 'foo', 'c': 'bar', 'd': 'bar'}

Let's assume I'm happy that my values are unique.

Community
  • 1
  • 1
LondonRob
  • 73,083
  • 37
  • 144
  • 201

1 Answers1

5

You can use a dictionary comprehension and the .items() method.

In []: {k: oldk for oldk, oldv in swapdict.items() for k in oldv}
Out[]: {'a': 'foo', 'b': 'foo', 'c': 'bar', 'd': 'bar'}
LondonRob
  • 73,083
  • 37
  • 144
  • 201
Delgan
  • 18,571
  • 11
  • 90
  • 141