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.
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.
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.
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.
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.
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})
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With