srynznfyra srynznfyra - 1 month ago 6
Python Question

Pythonic way to group list by key

I have a list that looks like this:

[
[1, "a", 319],
[1, "b", 991],
[2, "Cd", 19],
[3, "88x", 2891],
[3, "foo", 11]
]


What is the most "pythonic" way of turning this into:

[
[1, [["a", 319], ["b", 991]]],
[2, [["Cd", 19]]],
[3, [["88x", 2891], ["foo", 11]]]
]


I know how to do it using
for
loops and such, but I'm after a cleaner approach.

Answer

Here is one option assuming the list is sorted by the first element before hand:

from itertools import groupby    
[[k, [x[1:] for x in g]] for k, g in groupby(lst, key = lambda x: x[0])]

#[[1, [['a', 319], ['b', 991]]],
# [2, [['Cd', 19]]],
# [3, [['88x', 2891], ['foo', 11]]]]