类似于这个问题 https://stackoverflow.com/questions/1031851/python-best-way-to-exchange-keys-with-values-in-a-dictionary and 这个问题 https://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping,我想交换字典中的键和值。
不同的是,我的值是列表,而不仅仅是单个值。
因此,我想转向:
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'}
假设我很高兴我的价值观是独一无二的。
您可以使用字典理解 https://www.python.org/dev/peps/pep-0274/和.items() https://docs.python.org/2.7/library/stdtypes.html#dict.items method.
In []: {k: oldk for oldk, oldv in swapdict.items() for k in oldv}
Out[]: {'a': 'foo', 'b': 'foo', 'c': 'bar', 'd': 'bar'}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)