3 回答
TA贡献1839条经验 获得超15个赞
您可以使用 adefaultdict并切片key仅保留第一个字符的字符串:
from collections import defaultdict
d = defaultdict(int)
for k,v in input_dict.items():
d[k[0]] += v
print(d)
# defaultdict(int, {'3': 9, '5': 4, '6': 6})
TA贡献1770条经验 获得超3个赞
您可以使用字典中的get方法:
input_dict = {'3': 2, '5': 4, '36': 7, '62': 6}
result = {}
for k, v in input_dict.items():
key = k[0]
result[key] = v + result.get(key, 0)
print(result)
输出
{'3': 9, '5': 4, '6': 6}
TA贡献1155条经验 获得超0个赞
用这个:
new_dict = {}
for key, val in input_dict.items():
if key[0] not in new_dict:
new_dict[key[0]] = val
else:
new_dict[key[0]] += val
输出
{'3': 9, '5': 4, '6': 6}
添加回答
举报
