在python中的字典中切换键和值 [英] switching keys and values in a dictionary in python
本文介绍了在python中的字典中切换键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
my_dict = {2:3,5:6,8:9}
有没有办法可以切换按键和值来获取:
{3:2,6:5,9:8}
解决方案
my_dict2 = dict((y,x)for x,y in my_dict.iteritems())
如果您使用的是python 2.7或3.x,可以使用字典理解:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
pre>
编辑
如JBernardo的评论所述,对于python 3.x,您需要使用
项目
而不是iteritems
Say I have a dictionary like so:
my_dict = {2:3, 5:6, 8:9}
Is there a way that I can switch the keys and values to get:
{3:2, 6:5, 9:8}
解决方案my_dict2 = dict((y,x) for x,y in my_dict.iteritems())
If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:
my_dict2 = {y:x for x,y in my_dict.iteritems()}
Edit
As noted in the comments by JBernardo, for python 3.x you need to use
items
instead ofiteritems
这篇关于在python中的字典中切换键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文