我的输入是一个列表,我想将它转换成字典并为相同的键添加所有值。就像在随机列表中给出的示例 k
有两个值 1
和 3
所以 k
在字典中的值将是 {'k':4,'D':2}
。然后按字母顺序排序
Input: ['k:1','D:2','k:3']
Output {'k':4,'D':2}
dlist = ['k:1','D:2','k:3']
dick ={}
for x in dlist:
key,value = x.split(':')
dick[key] = int(value)
print(dick)
我有上面的代码,但我不知道如何为 k 添加两个值?
最佳答案
您需要实际添加该值到预先存在的值。在您的代码中,您现在只需用新值覆盖旧值。
dick = {}
for x in dlist:
key, value = x.split(':')
dick[key] = dick.get(key, 0) + int(value)
dict.get(key, 0)
gets the value of the key in the dictionary, with a default of zero
关于python - 在字典中添加相同键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63924052/