Python·100 questions

How to group list elements by key?

Answer
For small data: defaultdict(list).
group[key].append(item).
For groupby, sort first by key.
key function should be stable.
Result usually dict[key] -> list[items].
Was this answer helpful?

More questions in this topic

Related questions from other topics