我有一個串列串列LofL = [['a',20], ['a',50], ['b',14], ['c', 9], ['b', 1], ['d', 44], ['d', 5]],我想制作一個字典,其中字串作為鍵,值作為 LofL 中的值,用于將每個相應的字串添加在一起。前任:
dict1 = {'a': 70, 'b': 15, 'c': 9, 'd': 49}
順序無關緊要,因為如果鍵等于不同的輸入,我將從字典中呼叫值。我只是迷失了如何將這些值加在一起。到目前為止,我所能做的只是一個字典,它的最后一組鍵和值等于字典中的值。前任:
dict1 = {'a': 50, 'b': 1, 'c': 9, 'd': 44}
uj5u.com熱心網友回復:
這是另一種方法:
LofL = [['a',20], ['a',50], ['b',14], ['c', 9], ['b', 1], ['d', 44], ['d', 5]]
dict1 = {x: 0 for x, _ in LofL}
for char, num in LofL:
dict1[char] = num
print(dict1)
uj5u.com熱心網友回復:
如果您想添加給定鍵的所有值,那么我建議使用defaultdict如下
from collections import defaultdict
LofL = [['a',20], ['a',50], ['b',14], ['c', 9], ['b', 1], ['d', 44], ['d', 5]]
dict1 = defaultdict(int)
for k, v in LofL:
dict1[k] = v
結果
>>> dict1
defaultdict(<class 'int'>, {'a': 70, 'b': 15, 'c': 9, 'd': 49})
這dict1[k]將基本上允許動態插入具有相應值的鍵0,您可以在遍歷串列串列時使用它來累積重復的鍵值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/455934.html
標籤:Python
