[Python]Group nested List by first element

Heya,

tough topic to find a descriptive title for heh.

Imagine a nested List like this:


[
[Entry1,Value1],
[Entry2,Value2],
[Entry2,Value3],
[Entry4,Value4],
[Entry4,Value5]
]

Now i want to group by the first value in the sub-lists. So e.g. as a dict the result would look like this:


{
Entry1:[Value1],
Entry2:[Value2,Value3],
Entry4:[Value4,Value5],
}

This seems like a pretty common task but due to my lack of a proper description i also lack terms for google :wink:

Any input, tricks would be appreciated.

Regards,
Thorsten

defaultdict is what you are looking for…

from collections import defaultdict
d = defaultdict(list)
for k, v in nestedList:
    d[k].append(v)

print dict(d)

Perfect. I knew there was something more clever than nested if/in loops :smiley:

Thanks a lot!
Thorsten