Dev Helpers
← Back

Group with defaultdict

Group with defaultdict. A self-contained example using the Python standard library.

Open this example in the interactive library

Source code

from collections import defaultdict
groups = defaultdict(list)
for key, value in [('a',1),('b',2),('a',3)]:
    groups[key].append(value)
print(dict(groups))

Sample output

{'a': [1, 3], 'b': [2]}