penta
penta

Reputation: 2586

Summing multiple values of each key in a dict?

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]
}

Now my requirement is that i want to add the numeric values of this dict & to show it as :-

{    'item1' : [21],
     'item2' : [6],
      .
      .
      .
     'item n' : [15]
}

I just want the multiple values of each key to be summed up & displayed. FYI, I am using an append function. Below is my code.

for row in range(2,sheet2.max_row):
    for column in "D": 
        cell_name = "{}{}".format(column, row)
    for column2 in "P":
        cell_name2 = "{}{}".format(column2,row)
        arrdata2dict.setdefault(sheet2[cell_name].value,[])
        arrdata2dict[sheet2[cell_name].value].append(sheet2[cell_name2].value)

Upvotes: 2

Views: 7278

Answers (3)

Erik Godard
Erik Godard

Reputation: 6030

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

Upvotes: 3

Andrzej Dybionka
Andrzej Dybionka

Reputation: 271

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)

Upvotes: 2

ForceBru
ForceBru

Reputation: 44848

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)].

Upvotes: 2

Related Questions