Python - Get sum of tuples having same first value

Tuples are Python collections that are ordered but unchangeable. When working with a list of tuples where multiple tuples share the same first element, we often need to sum the second elements of tuples that have matching first elements.

Using Dictionary and For Loop

This approach converts tuples to a dictionary where first elements become keys and second elements are summed as values ?

# List of tuples with some duplicate first elements
data = [(3, 19), (7, 31), (7, 50), (1, 25.5), (1, 12)]

# Create dictionary with first elements as keys, initialize to 0
result_dict = {key: 0 for key, value in data}

# Sum values for each key
for key, value in data:
    result_dict[key] = result_dict[key] + value

# Convert back to list of tuples using map
result = list(map(tuple, result_dict.items()))
print(result)
[(3, 19), (7, 81), (1, 37.5)]

Using collections.defaultdict

The defaultdict approach automatically initializes missing keys to zero, making the code more concise ?

from collections import defaultdict

# List of tuples
data = [(3, 19), (7, 31), (7, 50), (1, 25.5), (1, 12)]

# Use defaultdict to automatically handle missing keys
result_dict = defaultdict(int)

for key, value in data:
    result_dict[key] += value

# Convert to list of tuples
result = list(result_dict.items())
print(result)
[(3, 19), (7, 81), (1, 37.5)]

Using Dictionary Comprehension

A more Pythonic approach using dictionary comprehension with sum() ?

data = [(3, 19), (7, 31), (7, 50), (1, 25.5), (1, 12)]

# Get unique first elements
unique_keys = set(key for key, value in data)

# Sum values for each unique key
result = [(key, sum(value for k, value in data if k == key)) 
          for key in unique_keys]

print(sorted(result))  # Sort for consistent output
[(1, 37.5), (3, 19), (7, 81)]

Comparison

Method Time Complexity Best For
Dictionary + For Loop O(n) Clear, readable code
defaultdict O(n) Cleaner syntax, automatic initialization
Dictionary Comprehension O(n²) Functional programming style

Conclusion

Use defaultdict for the most efficient and clean solution. Dictionary comprehension works well for small datasets but has higher time complexity for large data.

Updated on: 2026-03-15T17:15:09+05:30

580 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements