[英]Create a dictionary from a tuple with a similar key
假設我有這些元組:
('eggs', 20, 30)
('eggs', 40, 23)
('eggs', 10, 24)
('apple', 2, 22)
('apple', 42, 3)
我希望字典看起來像這樣:
{
eggs: [[20, 30], [40,23], [10,24]],
apple: [[2,22], [42,3]]
}
我怎么會得到這個
我試過這樣做:
dic = {}
for d in data:
dic[d[0]] += [[d[1], d[2]]
#d[0] being eggs or apple, d[1] and d[2] being the numbers
嘗試這個,
>>> t = [('eggs', 20, 30), ('eggs', 40, 23), ('eggs', 10, 24), ('apple', 2, 22), ('apple', 42, 3)]
>>> d = {}
>>> for k, v1, v2 in t:
d.setdefault(k,[]).append([v1,v2])
Output:
>>> d
{'eggs': [[20, 30], [40, 23], [10, 24]], 'apple': [[2, 22], [42, 3]]}
類似於@shaikmoed 的答案,但迭代器解包:
dic = {}
for key, *values in lst:
dic.setdefault(key, []).append(values)
所以給出:
lst = [
('eggs', 20, 30),
('eggs', 40, 23),
('eggs', 10, 24),
('apple', 2, 22),
('apple', 42, 3)
]
dic
變為:
{'eggs': [[20, 30], [40, 23], [10, 24]], 'apple': [[2, 22], [42, 3]]}
如果您使用defaultdict
,您的方法是正確的。
from collections import defaultdict
dic = defaultdict(list)
for d in datas:
dic[d[0]] += [[d[1], d[2]]]
print (dic)
#defaultdict(<class 'list'>, {'eggs': [[20, 30], [40, 23], [10, 24]], 'apple': [[2, 22], [42, 3]]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.