2

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
penta
  • 2,536
  • 4
  • 25
  • 50
  • Linking a very similar question: [Sum values in a dict of lists](https://stackoverflow.com/q/42603737/7851470) – Georgy Jun 08 '20 at 18:58

3 Answers3

3

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()}
Community
  • 1
  • 1
Erik Godard
  • 5,930
  • 6
  • 30
  • 33
2

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

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Hi ForceBru, yea i had tried sum() but that did not work, thanks to your this solution, it works – penta Dec 13 '16 at 09:26
2
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)
  • 1
    Answers that do not include any explanation are often sent to review and can possibly be deleted. Can you provide why this is the correct answer and in how far it improves the questioner's example? – ImportanceOfBeingErnest Dec 13 '16 at 13:35