当值为列表时,交换字典键和值

时间:2015-07-28 11:02:36

标签: python python-2.7

this questionthis question类似,我想在字典中交换键和值。

不同之处在于,我的值是列表,而不仅仅是单个值。

因此,我想转向:

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

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

成:

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

让我们假设我的价值观是独一无二的。

1 个答案:

答案 0 :(得分:3)

您可以使用dictionary comprehension.items()方法。

In []: {k: oldk for oldk, oldv in swapdict.items() for k in oldv}
Out[]: {'a': 'foo', 'b': 'foo', 'c': 'bar', 'd': 'bar'}
相关问题