Python merge element of the list [closed]

If you want to preserve the order of the first elements, something like this might work:

from collections import OrderedDict

def merge(seq):
    d = OrderedDict()
    for k,v in seq:
        d.setdefault(k, []).append(v)
    result = [[k]+v for k,v in d.iteritems()]
    return result

This loops over each pair in the sequence. For each k, we either get the list associated with it in the dictionary d (if we’ve already seen it) or make a new empty list and get that. (That’s what setdefault does.) In either case we append v to that list. Finally we loop over every key, value pair in our dictionary d and make a new list in the form you want. Example:

>>> s = [['a',10],['b',3],['c',4],['a',6],['d',11],['c',6],['a',7],['d',10]]
>>> merge(s)
[['a', 10, 6, 7], ['b', 3], ['c', 4, 6], ['d', 11, 10]]

Leave a Comment