Mahesh Mahesh - 2 months ago 21
Python Question

merge two tuples with same key

I have a list that contains two indices for each entry, along with a value. The first two elements in each tuple are the row and column in the table, respectively. The third item is the cell's value.

I want to merge the values of each of the same cells. Here is an example of the data structure:

[
(1, 2, 'R'),
(1, 3, 'S'),
(1, 2, 'S'),
(2, 3, 'S'),
]


I need to merge the items with matching row/column pairs like this:

[
(1, 2, 'RS'),
(1, 3, 'S'),
(2, 3, 'S'),
]


or:

[
(1, 2, ('R', 'S')),
(1, 3, ('S',)),
(2, 3, ('S',)),
]

Answer Source

Here's something that should work. If you're using Python 3, change the.iteritems()method calls to just.items()(which is already an iterator in that version of Python).

from collections import defaultdict

def merge_final_values(values):
    mergeddict = defaultdict(list)
    for group in values:
        mergeddict[group[:-1]].append(group[-1])
    return [(k + (tuple(v),) if len(v) > 1 else k + tuple(v))
                for k, v in mergeddict.iteritems()]

test = [(1, 2, 'R'), (1, 3, 'S'), (1, 2, 'S'), (2, 3, 'S')]

print(merge_final_values(test))

Output:

[(1, 2, ('R', 'S')), (1, 3, 'S'), (2, 3, 'S')]

if you want the merged values concatenated into a single string, just change the return value of the function to:

    return [(k + (''.join(v),)) for k, v in mergeddict.iteritems()]

And you'll get this output instead:

[(1, 2, 'RS'), (1, 3, 'S'), (2, 3, 'S')]