Python | Get sum of tuples having same first value

Given a list of tuple, the task is to sum the tuples having same first value.

Examples:

Input: [(1, 13), (2, 190), (3, 82), (1, 12)]
Output: [(1, 25), (2, 190), (3, 82)]

Input: [(1, 13), (1, 190), (3, 25), (1, 12)]
Output: [(1, 215), (3, 25)]

 
Let’s discuss the different ways we can do this task.



Method #1: Using map()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to get sum of tuples having same first value
  
# Initialisation of list of tuple
Input = [(1, 13), (1, 190), (3, 25), (1, 12)]
  
d = {x:0 for x, _ in Input}
  
for name, num in Input: d[name] += num
  
# using map
Output = list(map(tuple, d.items()))
  
# printing output
print(Output)

chevron_right


Output:

[(1, 215), (3, 25)]

 
Method #2: Using defaultdict

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to sum list of tuples having same first value
  
# Importing
from collections import defaultdict
  
# Initialisation of list of tuple
Input = [(2, 190), (1, 13), (1, 12), 
         (2, 14), (3, 82), (1, 70)]
  
# Initialisation of defaultdict
output = defaultdict(int)
  
for k, v in Input:
    output[k] += v
  
# Printing output
print(list(output.items()))

chevron_right


Output:

[(1, 95), (2, 204), (3, 82)]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.