Sum values in a dict of lists

試著忘記壹切 提交于 2020-06-11 11:08:11

问题


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}

回答1:


Use sum() function:

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()}

Output:

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



回答2:


Try This:

def sumDictionaryValues(d):
    new_d = {}
    for i in d:
        new_d[i]= sum(d[i])
    return new_d



回答3:


Just a for loop:

new = {}
for key in dict:
    new_d[key]= sum(d[key])

new the dictionary having all the summed values



来源:https://stackoverflow.com/questions/42603737/sum-values-in-a-dict-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!