newbie/ merging lists of lists with items in common

Bart Ogryczak B.Ogryczak at gmail.com
Fri Feb 2 09:50:53 EST 2007


On Feb 2, 2:55 pm, "ardief" <rachele.defel... at gmail.com> wrote:
> Hi everyone
> 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']]]

your_list = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c',
'15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'],
['e', '7']]
d = {}
for k,v in your_list: d.setdefault(k,[]).append(v)
result = [list(x) for x in d.items()] # if you really need it as list
of lists
# if list of tuples is ok, then it´d be just:
# result = d.items()
result.sort() # if you need this list sorted by keys





More information about the Python-list mailing list