Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum multiple values for same key in lists using python

Tags:

python

list

I have a list which looks like this:

(151258350, 2464)
(151258350, 56)
(151262958, 56)
(151258350, 56)
(151262958, 112)
(151262958, 112)
(151259627, 56)
(151262958, 112)
(151262958, 56)

And I want a result that looks like this:

151259627 56
151262958 448
151258350 2576

And here's my code:

for key, vals in d.items():
    tempList.append((key, reduce(add, vals))) 

here, d is the list with the key-value pair. tempList is the List in which the values will be appended after summing them by key. and add is a fuction:

def add(x, y): return x+y

If this question has already been asked, please point me there as I was unsuccessful in finding it myself.

like image 377
Niras Avatar asked Aug 14 '15 07:08

Niras


People also ask

Can the same key have multiple values python?

General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary. To do so, we need to use a container as a value and add our multiple values to that container. Common containers are lists, tuples, and sets.

How do you sum the values of each key in a Python dictionary?

It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict. values(). Then you can call the sum method to get the sum of these values.

Can the same key have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How do I sum a list of values in a dictionary?

To sum the values in a list of dictionaries: Use a generator expression to iterate over the list. On each iteration, access the current dictionary at the specific key. Pass the generator expression to the sum() function.


2 Answers

Use a Counter:

>>> l = [(151258350, 2464),
(151258350, 56),
(151262958, 56),
(151258350, 56),
(151262958, 112),
(151262958, 112),
(151259627, 56),
(151262958, 112),
(151262958, 56)]
>>> c = Counter()
>>> for k, v in l:
        c[k] += v

>>> c
Counter({151258350: 2576, 151262958: 448, 151259627: 56})
like image 112
poke Avatar answered Sep 27 '22 17:09

poke


num_list = [(151258350, 2464),
(151258350, 56),
(151262958, 56),
(151258350, 56),
(151262958, 112),
(151262958, 112),
(151259627, 56),
(151262958, 112),
(151262958,56)]
num_dict = {}
for t in num_list:
    if t[0] in num_dict:
        num_dict[t[0]] = num_dict[t[0]]+t[1]
    else:
        num_dict[t[0]] = t[1]

for key,value in num_dict.items():
    print "%d %d" %(key,value)
like image 44
Animesh Sharma Avatar answered Sep 27 '22 16:09

Animesh Sharma