python元组到字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3783530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python tuple to dict
提问by Jake
For the tuple, t = ((1, 'a'),(2, 'b'))dict(t)returns {1: 'a', 2: 'b'}
对于元组,t = ((1, 'a'),(2, 'b'))dict(t)返回{1: 'a', 2: 'b'}
Is there a good way to get {'a': 1, 'b': 2}(keys and vals swapped)?
有没有好的方法来获取{'a': 1, 'b': 2}(键和值交换)?
Ultimately, I want to be able to return 1given 'a'or 2given 'b', perhaps converting to a dict is not the best way.
最终,我希望能够返回1given'a'或2given 'b',也许转换为 dict 不是最好的方法。
采纳答案by Greg Hewgill
Try:
尝试:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
回答by jterrace
A slightly simpler method:
一个稍微简单的方法:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
回答by Gunnarsson
>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}
Or:
或者:
>>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]
回答by autholykos
Even more concise if you are on python 2.7:
如果您使用的是 python 2.7,则更加简洁:
>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}
回答by psun
If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,
如果同一个键有多个值,以下代码会将这些值附加到与其键对应的列表中,
d = dict()
for x,y in t:
if(d.has_key(y)):
d[y].append(x)
else:
d[y] = [x]
回答by Vlad Bezden
Here are couple ways of doing it:
这里有几种方法:
>>> t = ((1, 'a'), (2, 'b'))
>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}
>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}

