我有一個集合,看起來像這樣:使用序列中的列表值創建字典的最乾淨(大多數Pythonic)方法是什麼?
stuff = [('key1', 1), ('key2', 2), ('key3', 3),
('key1', 11), ('key2', 22), ('key3', 33),
('key1', 111), ('key2', 222), ('key3', 333),
]
# Note: values aren't actually that nice. That would make this easy.
我希望把它變成看起來像這樣一本字典:
dict_stuff = {'key1': [1, 11, 111],
'key2': [2, 22, 222],
'key3': [3, 33, 333],
}
什麼是將此數據轉換的最好方法是什麼?首先想到的方法是:
dict_stuff = {}
for k,v in stuff:
dict[k] = dict.get(k, [])
dict[k].append(v)
這是乾淨的方法嗎?
如果'stuff'是保證被 「重點」 進行排序,我會用'itertools.groupby'。由於看起來並非如此,'collections.defaultdict'可能是您的下一個最佳選擇(如答案中所示) – mgilson 2015-03-02 21:52:12