在Python中的字典中交换唯一值的键 [英] Swap keys for unique values in a dictionary in Python

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

问题描述

a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = {}
for key, val in a.items():
    b[val] = key
print b

我想要做的是交换键字典的值。但是使用这个代码,我会丢失字典的一些信息,得到这个输出:

What I am trying to do is to swap value of the dictionary for key. But using this code, I lose some information of the dictionary, getting this output:

{'LinMotion': 10, 'PtpMotion': 9, 'Wait': 11}

为什么会这样?

推荐答案

每个键只能在字典中出现一次。您可以存储每个键的索引列表:

Each key can only occur once in a dictionary. You could store a list of indices for each key:

import collections
b = collections.defaultdict(list)
for key, val in a.iteritems():
    b[val].append(key)
print b
# {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 'PtpMotion': [0, 1, 9], 'Wait': [11]}

编辑:正如ecik在评论中所指出的,您还可以使用 defaultdict(set)(并使用 .add()而不是循环中的 .append()

As pointed out by ecik in the comments, you could also use a defaultdict(set) (and use .add() instead of .append() in the loop).

这篇关于在Python中的字典中交换唯一值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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