问题:python元组到字典
对于元组,t = ((1, 'a'),(2, 'b'))
dict(t)
返回{1: 'a', 2: 'b'}
有没有一种好的方法{'a': 1, 'b': 2}
(交换键和值)?
最终,我希望能够返回1
给定'a'
或2
给定'b'
,也许转换为字典不是最好的方法。
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.
回答 0
尝试:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
Try:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
回答 1
稍微简单一些的方法:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
A slightly simpler method:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
回答 2
如果您使用的是python 2.7,则更加简洁:
>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}
Even more concise if you are on python 2.7:
>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}
回答 3
>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}
要么:
>>> [ 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}]
>>> 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}]
回答 4
如果同一个键有多个值,则以下代码会将这些值附加到与它们的键相对应的列表中,
d = dict()
for x,y in t:
if(d.has_key(y)):
d[y].append(x)
else:
d[y] = [x]
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]
回答 5
以下是几种方法:
>>> 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}
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}