如果我有一本字典,例如:
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}
这篇关于列表字典中的总和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!