Sum values in a dict of lists

前端 未结 4 1171
名媛妹妹
名媛妹妹 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}
    
    0 讨论(0)
  • 2021-01-07 10:44

    One liners- for the same, just demonstrating some ways to get the expected result,

    my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
    
    1. Using my_dict.keys():- That returns a list containing the my_dict's keys, with dictionary comprehension.

      res_dict = {key : sum(my_dict[key]) for key in my_dict.keys()}
      
    2. Using my_dict.items():- That returns a list containing a tuple for each key value pair of dictionary, by unpacking them gives a best single line solution for this,

      res_dict = {key : sum(val) for key, val in my_dict.items()}
      
    3. Using my_dict.values():- That returns a list of all the values in the dictionary(here the list of each lists),

      note:- This one is not intended as a direct solution, just for demonstrating the three python methods used to traverse through a dictionary

      res_dict = dict(zip(my_dict.keys(), [sum(val) for val in my_dict.values()]))
      

    The zip function accepts iterators(lists, tuples, strings..), and pairs similar indexed items together and returns a zip object, by using dict it is converted back to a dictionary.

    0 讨论(0)
  • 2021-01-07 10:45

    Just a for loop:

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

    new the dictionary having all the summed values

    0 讨论(0)
  • 2021-01-07 10:55

    Try This:

    def sumDictionaryValues(d):
        new_d = {}
        for i in d:
            new_d[i]= sum(d[i])
        return new_d
    
    0 讨论(0)
提交回复
热议问题