Python - Get sum of tuples having same first value

PythonServer Side ProgrammingProgramming

Tuples are python collections or arrays which are ordered but unchangeable. If we get a number of tuples where the first element is the same, then we may have a scenario when we need to add the second elements of those tuples whose first elements are equal.

Using map and for loop

In this method we will first consider a list made up of tuples. Then convert them to dictionary so that we can associate the elements in the tuple as key value pair. Then we apply the for loop with summing the value for each key o the dictionary. Finally use the map function to get back the list which has the summed up values.

Example

 Live Demo

List = [(3,19),(7, 31), (7, 50), (1, 25.5), (1, 12)]
# Converting it to a dictionary
tup = {i:0 for i, v in List}
for key, value in List:
   tup[key] = tup[key]+value
# using map
result = list(map(tuple, tup.items()))
print(result)

Running the above code gives us the following result:

Output

[(3, 19), (7, 81), (1, 37.5)]

Using collections

Here we take a similar approach as above but use the defaultdict method of collections module. Now instead of using the map function, we access the dictionary items and convert them to a list.

Example

 Live Demo

from collections import defaultdict
# list of tuple
List = [(3,19),(7, 31), (7, 50), (1, 25.5), (1, 12)]
dict = defaultdict(int)
for key, value in List:
   dict[key] = dict[key]+value
# Printing output
print(list(dict.items()))

Running the above code gives us the following result

Output

[(3, 19), (7, 81), (1, 37.5)]
raja
Published on 23-Dec-2019 10:13:05
Advertisements