LondonRob
LondonRob

Reputation: 78763

Swap dictionary keys and values when values are lists

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.

Upvotes: 2

Views: 2544

Answers (1)

Delgan
Delgan

Reputation: 19627

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'}

Upvotes: 5

Related Questions