在python中切换字典中的键和值
问题描述:
假设我有一本这样的字典:
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())
如果您使用的是 python 2.7 或 3.x,您可以改用字典理解:
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()}
编辑
如 JBernardo 的评论中所述,对于 python 3.x,您需要使用 items
而不是 iteritems
As noted in the comments by JBernardo, for python 3.x you need to use items
instead of iteritems