Jonwickwithastick
Jonwickwithastick

Reputation: 3

How do I sum a list of tuple pairs?

I have a list of pairs which is constantly updating with new values every second. I need to sum the second value in each tuple if they are equal to the first value in each tuple. I've tried using a dictionary but because the keys are unique it overwrites the previous update.

[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74)]
[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74), (3.1, 293.97)]
[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74), (3.1, 293.97), (3.05, 16.32)]
[(3.05, 0.0), (3.1, 863.62), (3.05, 156.74), (3.1, 293.97), (3.05, 16.32), (3.05, 210.72)]

Desired output:

[(3.05, 383.06), (3.1, 1157.59)]

I've had to recreate the problem, in the original post the numbers are flowing in from excel per second. When i use a dictionary, the new update key replaces the old and records a new value against the unique key. So it make it difficult to sum all the value against their keys. This is just an example, the update will be whatever excel offers.

import collections ,random, string

alpha = list(string.ascii_letters)

lst_a = []
lst_b = []

for i in range(100):
    lst_a.append(alpha[random.choice(range(25))])
    lst_b.append(random.choice(range(1000)))


combine = dict(zip(lst_a,lst_b))
print(combine.get('a'))

update = list(zip(['a'],[2000]))
combine.update(update)

print(combine.get('a'))

Using key 'a' for example, the values are not a sum of each other.

Upvotes: 0

Views: 130

Answers (1)

Cyril Jouve
Cyril Jouve

Reputation: 1040

you can use a defaultdict

d = defaultdict(float)
for a, b in list_of_pairs:
    d[a] += b
desired_output = list(d.items())

Upvotes: 3

Related Questions