如果我有一本字典,例如:
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模板网!
如何在 Python 中对文本文件中的数字求和How to sum numbers from a text file in Python(如何在 Python 中对文本文件中的数字求和)
什么是类似于 sum() 的减法函数,用于减去列表中What is a subtraction function that is similar to sum() for subtracting items in list?(什么是类似于 sum() 的减法函数,用于减去列表中的
Python 等价于 sum() 使用 xor()Python equivalent of sum() using xor()(Python 等价于 sum() 使用 xor())
python中的求和矩阵列sum matrix columns in python(python中的求和矩阵列)
N个列表元素的总和pythonsum of N lists element-wise python(N个列表元素的总和python)
带有列表参数的 Python sum() 函数Python sum() function with list parameter(带有列表参数的 Python sum() 函数)