[英]Python list of tuples: organize by unique elements to a dictionary
I have a list of tuples, say: 我有一个元组列表,说:
list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
I need to get correspoding values for any (unique) second element in a tuple. 我需要获取元组中任何(唯一)第二个元素的对应值。 For example as a dictionary.
例如作为字典。 Output:
输出:
dict = {1:['a','c'],2:['b','a'],3:['d']}
Whats the most pythonic way of doing it? 最Python的方式是什么? Help much appriciated!
帮忙多谢!
I'd probably go with a defaultdict
like jamylak, but if you want a "real" dictionary, you can use setdefault()
: 我可能会使用像jamylak这样的
defaultdict
,但是如果您想要“真实的”字典,则可以使用setdefault()
:
>>> list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
>>> d = {}
>>> for item in list_of_tuples:
... d.setdefault(item[1],[]).append(item[0])
...
>>> d
{1: ['a', 'c'], 2: ['b', 'a'], 3: ['d']}
>>> from collections import defaultdict
>>> list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
>>> d = defaultdict(list)
>>> for c,num in list_of_tuples:
d[num].append(c)
>>> d
defaultdict(<type 'list'>, {1: ['a', 'c'], 2: ['b', 'a'], 3: ['d']})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.