列表字典中的总和值

2022-01-09 00:00:00 python dictionary sum

问题描述

如果我有一本字典,例如:

If I have a dictionary such as:

my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}

如何创建一个包含每个键的值总和的新字典?

How do I create a new dictionary with sums of the values for each key?

result = {"A": 6, "B": 7, "C": 103}


解决方案

使用sum()函数:

my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}

result = {}
for k, v in my_dict.items():
    result[k] = sum(v)

print(result)

或者只是创建一个带有字典理解的字典:

Or just create a dict with a dictionary comprehension:

result = {k: sum(v) for k, v in my_dict.items()}

输出:

{'A': 6, 'B': 7, 'C': 103}

相关文章