3
[('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]

for example, I have the list of tuples above, how can i find the duplicates(i.e 'Visa') and sum their values (i.e 980.5+215.0)? The output should be:

[('Visa', 1195.5), ('Rogers', 61.5)]
0

6 Answers 6

10

Use a dictionary:

>>> data = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
>>> result = {}
>>> for card, value in data:
        total = result.get(card, 0) + value
        result[card] = total

    
>>> print result.items()
[('Visa': 1195.5), ('Rogers': 61.5)]
5

Looks like everybody forgot about collections.Counter:

from collections import Counter


c = Counter()
for card, val in lst:
    c[card] += val
print(list(c.items()))

# [('Visa', 1195.5), ('Rogers', 61.5)]
2
  • I was trying to use this for map-reduce, but the error says "too many values to unpack".
    – Agent 0
    Nov 16, 2018 at 23:54
  • 1
    @ForgottenApe: Sounds like your lst isn't an iterable of pairs; you'd see that error if, say, you had a list of str and were trying to count unique strings, rather than a list of tuples representing a key and the associated numerical value; using a list of anything where the values were iterables containing exactly two values causes the problem, and the common mistake that causes this is when it's a list of str (which the loop tries to unpack). If you're counting a list of single items, not key + numerical values, you can just do c = Counter(lst) and it will count for you. Dec 27, 2021 at 20:20
3

A collections.defaultdict would be the most efficient way:

from collections import defaultdict

l= [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]

d = defaultdict(float)
for k,v in l:
    d[k] += v

Output:

defaultdict(<class 'float'>, {'Visa': 1195.5, 'Rogers': 61.5})
0
1
data = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
sum = {}
for item in data:
    if not item[0] in sum:
          sum[ item[0] ] = 0
    sum[ item[0] ] += item[1]
print sum.items()
1
  • To add to this answer, if printing is not desirable, then list(sum.items()) will do the trick. (sum.items() is not a list.) Nov 26, 2015 at 2:01
1

use set:

li=[('Rogers', 10), ('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
s=set([i[0] for i in li])

x=[]
for i in s:
    sum=0
    for j in li:    
        if i == j[0]:
            sum+=j[1]
    x.append(sum)

final_list=zip(s,x)
print final_list

output:

[('Visa', 1195.5), ('Rogers', 61.5)]
0

If you want to maintain the order of the list then I suggest this over using a dictionary.

lst = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]

lst2 = [(tup[0], sum([val for n, val in lst if n == tup[0]])) for tup in lst]

res = []
for tup in lst2:
    if tup not in res:
        res.append(tup)

print(res)

Not the answer you're looking for? Browse other questions tagged or ask your own question.