1

I have multiple lists of tuples containing a name and a count and I want to merge them by their name with the sum of their respective count. For example, I have :

l1 = [('House', 3),('Backyard', 2),('Frontyard', 4)]
l2 = [('House', 10),('street', 7),('Frontyard', 4)]
l3 = [('Backyard', 10),('street', 7),('Frontyard', 4)]

And I would like to get:

result : [('house', 13),('Backyard', 12), ('street', 14), ('Frontyard', 12)]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70

1 Answers1

0

Just use a single dictionary for totalizing...

result = {}
for L in l1, l2, l3:
    for key, value in L:
        result[key] = result.get(key, 0) + value

# convert to a list
result = list(result.items())
6502
  • 112,025
  • 15
  • 165
  • 265