在python中切换字典中的键和值 [英] switching keys and values in a dictionary in python

查看:42
本文介绍了在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

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

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