[英]Python list of tuples: organize by unique elements to a dictionary
我有一個元組列表,說:
list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
我需要獲取元組中任何(唯一)第二個元素的對應值。 例如作為字典。 輸出:
dict = {1:['a','c'],2:['b','a'],3:['d']}
最Python的方式是什么? 幫忙多謝!
我可能會使用像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.