我有一个列表列表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}发布于 2022-04-05 18:08:31
如果您想为给定的键添加所有值,那么我建议使用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://stackoverflow.com/questions/71756441
复制相似问题