Created
November 6, 2020 09:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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