
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Get sum of tuples having same first value
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
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
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)]
- Related Articles
- Remove tuples having duplicate first value from given list of tuples in Python
- Python Group tuples in list with same first value
- Get first element with maximum value in list of tuples in Python
- Python - Restrict Tuples by frequency of first element’s value
- Extract tuples having K digit elements in Python
- Python program to get all subsets having sum s\n
- How to get Subtraction of tuples in Python
- Selective value selection in list of tuples in Python
- Combinations of sum with tuples in tuple list in Python
- Python – Remove Tuples from a List having every element as None
- Remove Tuples from the List having every element as None in Python
- Get first value in Java TreeSet
- Get three records having higher value from MySQL
- Python Group by matching second tuple value in list of tuples
- Count distinct pairs from two arrays having same sum of digits in C++
