Files
30-seconds-of-code/snippets/group_by.md
Isabelle Viktoria Maciohsek 1af3e1105d Update group_by
Fixes #201
2020-10-03 17:11:38 +03:00

27 lines
656 B
Markdown

---
title: group_by
tags: list,dictionary,intermediate
---
Groups the elements of a list based on the given function.
- 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):
d = defaultdict(list)
for el in lst:
d[fn(el)].append(el)
return dict(d)
```
```py
from math import floor
group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}
```