From 1af3e1105d2e09a8f97f7ea6b48bb7fce3975a71 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sat, 3 Oct 2020 17:11:38 +0300 Subject: [PATCH] Update group_by Fixes #201 --- snippets/group_by.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/snippets/group_by.md b/snippets/group_by.md index a6ca81b4a..03b8c8184 100644 --- a/snippets/group_by.md +++ b/snippets/group_by.md @@ -5,12 +5,18 @@ tags: list,dictionary,intermediate Groups the elements of a list based on the given function. -- Use `map()` and `fn` to map the values of the list to the keys of a dictionary. -- Use list comprehension to map each element to the appropriate `key`. +- Use `defaultdict()` to initialize a dictionary. +- Use `fn` in combination with a `for` loop and `dict.append()` to populate the dictionary. +- Use the `dict()` constructor to convert it to a regular dictionary. ```py +from collections import defaultdict + def group_by(lst, fn): - return {key : [el for el in lst if fn(el) == key] for key in map(fn, lst)} + d = defaultdict(list) + for el in lst: + d[fn(el)].append(el) + return dict(d) ``` ```py