def test_set_groupby(): from groupby import set_groupby pairs = [ ('x', 'apple'), ('y', 'banana'), ('x', 'apple'), ('x', 'banana') ] actual = set_groupby(pairs) expected = { 'x' : { 'apple', 'banana' }, 'y' : { 'banana' } } assert actual == expected data = 'apple banana orange apricot blueberry weasel apple'.split() actual = set_groupby(data, key=lambda x:x[0]) expected = { 'a' : { 'apple', 'apricot' }, 'b' : { 'banana', 'blueberry' }, 'o' : { 'orange' }, 'w' : { 'weasel' }, } assert actual == expected
def test_generic_groupby(): from groupby import generic_groupby, set_groupby data = 'apple banana orange apricot blueberry weasel apple'.split() pairs = [ (x[0], x) for x in data ] def accumulate(accumulator, value): if accumulator is None: return { value } else: accumulator.add(value) return accumulator actual = generic_groupby(pairs, accumulate) expected = set_groupby(pairs) assert actual == expected actual = generic_groupby(data, accumulate, key=lambda x:x[0]) assert actual == expected