classify¶
- emlib.iterlib.classify(s, keyfunc)[source]¶
Split s according to keyfunc
- Parameters:
s (
Sequence
[TypeVar
(T
)]) – the sequence to splitkeyfunc (
Callable
[[TypeVar
(T
)],TypeVar
(T2
)]) – a function taking an item of s and returning the key under which all similar items will be grouped
- Return type:
dict
[TypeVar
(T2
),list
[TypeVar
(T
)]]
Example
>>> s = [ ... {'name': 'John', 'city': 'New York'}, ... {'name': 'Otto', 'city': 'Berlin'}, ... {'name': 'Jakob', 'city': 'Berlin'}, ... {'name': 'Bob', 'city': 'New York'} ... ] >>> groups = classify(s, lambda record: record['city']) {'Berlin': [{'name': 'Otto', 'city': 'Berlin'}, {'name': 'Jakob', 'city': 'Berlin'}], 'New York': [{'name': 'John', 'city': 'New York'}, {'name': 'Bob', 'city': 'New York'}]}