Reputation: 78763
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
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