Skip to content

Instantly share code, notes, and snippets.

@oliora
Created November 6, 2020 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliora/03d5443890228fff745a585eb071382c to your computer and use it in GitHub Desktop.
Save oliora/03d5443890228fff745a585eb071382c to your computer and use it in GitHub Desktop.
A Python one liner to group list of items into a dictionary of lists
# One-liner
# items = [(1, 'a'), (2, 'b'), (3, 'c'), (1, 'd'), (3, 'e'), (1, 'f')]
reduce(lambda d, item: d.setdefault(item[0], []).append(item) or d, items, {})
# >>> {1: [(1, 'a'), (1, 'd'), (1, 'f')], 2: [(2, 'b')], 3: [(3, 'c'), (3, 'e')]}
# Featured function
def groupby_to_dict(iterable, key=None, value=None):
"""
Group items from `iterable` into a dictionary of lists. The order of items is preserved.
The `key` is a function computing a key value for each item. If not specified or is `None`, key defaults to an identity function and returns the item unchanged.
The `value` is a function extracting a value for each item to be appended to the list. If not specified or is `None`, takes the item unchanged.
"""
if key is None:
key = lambda x: x
if value is None:
value = lambda x: x
return reduce(lambda d, item: d.setdefault(key(item), []).append(value(item)) or d, iterable, {})
items = [(1, 'a'), (2, 'b'), (3, 'c'), (1, 'd'), (3, 'e'), (1, 'f')]
groupby_to_dict(items, lambda x: x[0])
# >>> {1: [(1, 'a'), (1, 'd'), (1, 'f')], 2: [(2, 'b')], 3: [(3, 'c'), (3, 'e')]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment