Sum values in a dict of lists

前端 未结 4 1173
名媛妹妹
名媛妹妹 2021-01-07 10:21

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 su

4条回答
  •  天涯浪人
    2021-01-07 10:43

    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}
    

提交回复
热议问题