Python:字典中的值与键交换密钥的最佳方式? [英] Python: Best Way to Exchange Keys with Values in a Dictionary?
本文介绍了Python:字典中的值与键交换密钥的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到一个字典作为输入,并希望返回一个字典,其键将是输入的值,其值将是相应的输入键。值是唯一的。
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.
例如,我的输入是:
a = dict()
a['one']=1
a['two']=2
我希望我的输出是:
{1: 'one', 2: 'two'}
为了澄清我希望我的结果等同于以下内容:
To clarify I would like my result to be the equivalent of the following:
res = dict()
res[1] = 'one'
res[2] = 'two'
实现这一点的任何纯粹的Python方法?
Any neat Pythonian way to achieve this?
感谢
推荐答案
res = dict((v,k) for k,v in a.iteritems())
这篇关于Python:字典中的值与键交换密钥的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文