使用in关键字

任务:将原字典列表转换为一个字典,相同关键字的值累加

origin_list = [{"Tom": 12}, {"Tom": 13}, {"Alice": 25}, {"Alice": 13}]

result_dict = {}
for item in origin_list:
for key, value in item.items():
if key in result_dict:
result_dict[key] += value
else:
result_dict[key] = value

print(result_dict)

使用try except

origin_list = [{"Tom": 12}, {"Tom": 13}, {"Alice": 25}, {"Alice": 13}]

result_dict = {}
for item in origin_list:
for key, value in item.items():
try:
result_dict[key] += value
except KeyError:
result_dict[key] = value

print(result_dict)