python元组到字典 [英] python tuple to dict
本文介绍了python元组到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于元组,t = ((1, 'a'),(2, 'b'))
dict(t)
返回 {1: 'a', 2: 'b'}
有什么好办法可以得到 {'a': 1, 'b': 2}
(keys and vals 交换)?
最终,我希望能够返回 1
给定 'a'
或 2
给定 'b'
>,也许转换为 dict 不是最好的方法.
解决方案
尝试:
<预><代码>>>>t = ((1, 'a'),(2, 'b'))>>>dict((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)?
Ultimately, I want 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元组到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文