python元组到dict [英] python tuple to dict

查看:112
本文介绍了python元组到dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于元组, t =((1,'a'),(2,'b'))
dict (t)返回 {1:'a',2:'b'}



<有没有一个很好的方法来获取 {'a':1,'b':2} (键和vals交换)?



我想要能够返回1给定'a'或2给定'b',也许转换为dict不是最好的方式。

解决方案

尝试:

 >>> t =((1,'a'),(2,'b'))
>>> ((y,x)for x,y in t)
{'a':1,'b':2}


For the tuple, t = ((1, 'a'),(2, 'b')) dict(t) returns {1: 'a', 2: 'b'}

Is there a good way to get {'a': 1, 'b': 2} (keys and vals swapped)?

I'm wanting to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the best way.

解决方案

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

这篇关于python元组到dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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