Python Easiest Way to Sum List Intersection of List of Tuples

intersection, list, python, set

Solution

Use a dictionary for the result:

result = {}
for k, v in my_list + other_list:
    result[k] = result.get(k, 0) + v

If you want a list of tuples, you can get it via `result.items()`. The resulting list will be in arbitrary order, but of course you can sort it if desired.

(Note that I renamed your lists to conform with Python's style conventions.)

Problem

Let's say I have the following two lists of tuples ``` myList = [(1, 7), (3, 3), (5, 9)] otherList = [(2, 4), (3, 5), (5, 2), (7, 8)] returns => [(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)] ``` I would like to design a merge operation that merges these two lists by checking for any intersections on the first element of the tuple, if there are intersections, add the second elements of each tuple in question (merge the two). After the operation I would like to sort based upon the first element. I am also posting this because I think its a pretty common problem that has an obvious solution, but I feel that there could be very pythonic solutions to this question ;)

Original source