Summing multiple values of each key in a dict?

后端 未结 3 538
醉酒成梦
醉酒成梦 2021-01-21 13:19

I have a python dictionary, which looks like this.

{ \'item1\' : [1,2,3,4,5,6],
  \'item2\' : [2,3,1],
   .
   .
   .
  \'item n\' : [4,2,4,3,2]
}
相关标签:
3条回答
  • 2021-01-21 13:32

    This seems unnecessarily complicated. If you have your input as

    inpt = { 'item1' : [1,2,3,4,5,6],
             'item2' : [2,3,1],
             .
             .
             .
             'item n' : [4,2,4,3,2]
           }
    

    you can then use a dictionary comprehension instead:

    out = {k: [sum(inpt[k])] for k in inpt.keys()}
    
    0 讨论(0)
  • 2021-01-21 13:39
    items = {'item1' : [1,2,3,4,5,6],
      'item2' : [2,3,1],
      'item3' : [4,2,4,3,2]
    }
    
    for key, values in items.items():
        items[key] = sum(values)
    
    0 讨论(0)
  • 2021-01-21 13:49

    You could create the dictionary with the sums on-the-fly:

    Result = dict([(key, sum(values)) for key, values in yourDict.items()])
    # or...
    Result = {key: sum(values) for key, values in yourDict.items()}
    

    Here, the values of the new dictionary will be numbers, but if you really need them to be lists, you could enclose the call to sum in square brackets: [sum(values)].

    0 讨论(0)
提交回复
热议问题