1
votes

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.

1
{k: oldk for oldk, oldv in swapdict.items() for k in oldv} - I haven't tested this, but I think it will workAlik
@Alik Yep! Seems to work just fine.LondonRob
If anyone would like to add this as an answer I'll accept it. Otherwise I'll do it myself in a day or two!LondonRob
@Alik i think you should answer itThe6thSense

1 Answers

4
votes

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