newbie/ merging lists of lists with items in common

Miki miki.tebeka at gmail.com
Fri Feb 2 09:10:25 EST 2007


Hello,
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with the
> only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
I'd use a dictionary to store value for a given key:
>>> def aggregate(lst):
    items = {} # key -> values
    for key, value in lst:
        values = items.get(key)
        if values:
            if type(values) == list:
                values.append(value)
            else:
                items[key] = [values, value]
        else:
            items[key] = value
    return [list(pair) for pair in items.items()]

>>> aggregate(lst)
[['a', ['13', '3']], ['c', ['12', '15', '4']], ['b', '6'], ['e',
['11', '5', '16', '7']], ['d', '2']]
>>>

HTH,
--
Miki <miki.tebeka at gmail.com>
http://pythonwise.blogspot.com




More information about the Python-list mailing list