Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

group by docs #150

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/seqs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -416,13 +416,23 @@ Split and chunk

One can use :func:`split` when grouping by boolean predicate. See also :func:`py3:itertools.groupby`.

You can also easily group dictionaries:

::

group_by(itemgetter("age"), [{"age": 10, "name": "Alice"}, {"age": 12, "name": "Bob"}])
# -> {10: [{'age': 10, 'name': 'Alice'}], 12: [{'age': 12, 'name': 'Bob'}]}


.. function:: group_by_keys(get_keys, seq)

Groups elements of ``seq`` having multiple keys each into :class:`defaultdict(list) <py3:collections.defaultdict>`. Can be used to reverse grouping::

posts_by_tag = group_by_keys(attrgetter('tags'), posts)

sentences = ["hello man", "hello woman"]
sentences_with_word = group_by_keys(str.split, sentences)
# -> {'hello': ['hello man', 'hello woman'], 'man': ['hello man'], 'woman': ['hello woman']}


.. function:: group_values(seq)
Expand Down
8 changes: 7 additions & 1 deletion tests/test_seqs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections.abc import Iterator
from operator import add
from operator import add, itemgetter
import pytest
from whatever import _

Expand Down Expand Up @@ -140,9 +140,15 @@ def test_split_by():
def test_group_by():
assert group_by(_ % 2, range(5)) == {0: [0, 2, 4], 1: [1, 3]}
assert group_by(r'\d', ['a1', 'b2', 'c1']) == {'1': ['a1', 'c1'], '2': ['b2']}
assert group_by(
itemgetter("x"), [{"x": 1, "y": 1}, {"x": 2, "y": 2}, {"x": 1, "y": 3}]
) == {1: [{"x": 1, "y": 1}, {"x": 1, "y": 3}], 2: [{"x": 2, "y": 2}]}

def test_group_by_keys():
assert group_by_keys(r'(\d)(\d)', ['12', '23']) == {'1': ['12'], '2': ['12', '23'], '3': ['23']}
assert group_by_keys(str.split, ["hello man", "hello woman"]) == {
'hello': ['hello man', 'hello woman'], 'man': ['hello man'], 'woman': ['hello woman']
}

def test_group_values():
assert group_values(['ab', 'ac', 'ba']) == {'a': ['b', 'c'], 'b': ['a']}
Expand Down
Loading