当值是列表时交换字典键和值 [英] Swap dictionary keys and values when values are lists

查看:43
本文介绍了当值是列表时交换字典键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于这个问题这个问题,我想交换字典中的键和值.

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.

因此,我想转:

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

假设我很高兴我的价值观是独一无二的.

Let's assume I'm happy that my values are unique.

推荐答案

您可以使用 字典理解.items() 方法.

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

这篇关于当值是列表时交换字典键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆