Python Grouped summation of tuple list¶

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program that adds all the values with the same keys different lists. Let's see an example to understand it clearly.

Input

list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]

Output

[('a', 6), ('b', 5), ('c', 12)]

Follow the given steps to solve the problem.

• Initialize the lists.
• Convert the first list into dictionary using dict and store it in a variable.
• Iterate over the second list and add the corresponding value to the key present in the dictionary.
• Print the result.

Example

Live Demo

# initializing the lists
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
# convering list_one to dict
result = dict(list_one)
# iterating over the second list
for tup in list_two:
# checking for the key in dict
if tup[0] in result:
result[tup[0]] = result.get(tup[0]) + tup[1]
# printing the result as list of tuples
print(list(result.items()))

Output

If you run the above code, then you will get the following result.

[('a', 6), ('b', 5), ('c', 12)]

We can solve the above problem without iterating over any list using Counter from collections. Let's see it.

Example

Live Demo

# importing the Counter
from collections import Counter
# initializing the lists
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
# getting the result
result = Counter(dict(list_one)) + Counter(dict())
# printing the result as list of tuples
print(list(result.items()))

Output

If you run the above code, then you will get the following result.

[('a', 6), ('b', 5), ('c', 12)]

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

Published on 06-Jul-2020 09:43:11