A comprehensive Python utility library for functional programming inspired by JavaScript's Lo-Dash
—
The Collections module provides 33 functions that operate on both arrays and objects (dictionaries). These functions are designed to work with any iterable collection and include operations for filtering, mapping, grouping, and reducing data.
def at(collection: Union[Mapping, Iterable], *paths) -> List[Any]Creates a list of elements corresponding to the given keys or indexes. For arrays, provide indexes; for objects, provide property paths.
Parameters:
collection (Union[Mapping, Iterable]): Collection to iterate over.paths (*Union[str, int]): Property paths to pick or indexes to select.Returns:
List[Any]: New list of picked elements.Example:
from pydash import at
# Array indexing
at(['a', 'b', 'c'], 0, 2)
# ['a', 'c']
# Object property access
at({'a': 1, 'b': 2, 'c': 3}, 'a', 'c')
# [1, 3]def every(collection: Iterable, predicate=None) -> boolChecks if predicate returns truthy for all elements of collection. Iteration is stopped once predicate returns falsey.
Parameters:
collection (Iterable): Collection to iterate over.predicate (Callable, optional): Function invoked per iteration.Returns:
bool: True if all elements pass the predicate check, else False.Example:
from pydash import every
every([2, 4, 6], lambda x: x % 2 == 0)
# True
every([2, 3, 6], lambda x: x % 2 == 0)
# False
# Using property shorthand
every([{'active': True}, {'active': True}], 'active')
# Truedef filter_(collection: Iterable, predicate=None) -> List[Any]Iterates over elements of collection, returning a list of all elements predicate returns truthy for.
Parameters:
collection (Iterable): Collection to iterate over.predicate (Callable, optional): Function invoked per iteration.Returns:
List[Any]: New filtered list.Example:
from pydash import filter_
filter_([1, 2, 3, 4], lambda x: x % 2 == 0)
# [2, 4]
# Using dict predicate
users = [{'name': 'John', 'active': True}, {'name': 'Jane', 'active': False}]
filter_(users, {'active': True})
# [{'name': 'John', 'active': True}]def find(collection: Iterable, predicate=None, from_index: int = 0) -> AnyIterates over elements of collection, returning the first element predicate returns truthy for.
Parameters:
collection (Iterable): Collection to inspect.predicate (Callable, optional): Function invoked per iteration.from_index (int): Index to search from. Defaults to 0.Returns:
Any: Matched element, else None.Example:
from pydash import find
find([1, 2, 3, 4], lambda x: x > 2)
# 3
users = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]
find(users, lambda u: u['age'] < 30)
# {'name': 'Jane', 'age': 25}def find_last(collection: Iterable, predicate=None, from_index: int = -1) -> AnyLike find except that it iterates over elements from right to left.
Parameters:
collection (Iterable): Collection to inspect.predicate (Callable, optional): Function invoked per iteration.from_index (int): Index to search from. Defaults to -1.Returns:
Any: Matched element, else None.Example:
from pydash import find_last
find_last([1, 2, 3, 4], lambda x: x > 2)
# 4def includes(collection: Iterable, target: Any, from_index: int = 0) -> boolChecks if target is in collection using SameValueZero for equality comparisons.
Parameters:
collection (Iterable): Collection to inspect.target (Any): Value to search for.from_index (int): Index to search from. Defaults to 0.Returns:
bool: True if target is found, else False.Example:
from pydash import includes
includes([1, 2, 3], 1)
# True
includes([1, 2, 3], 1, 2)
# False
includes({'a': 1, 'b': 2}, 1)
# Truedef map_(collection: Iterable, iteratee=None) -> List[Any]Creates a list of values by running each element in collection through iteratee.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
List[Any]: New mapped list.Example:
from pydash import map_
map_([1, 2, 3], lambda x: x ** 2)
# [1, 4, 9]
# Using property shorthand
users = [{'name': 'John'}, {'name': 'Jane'}]
map_(users, 'name')
# ['John', 'Jane']def size(collection: Sized) -> intGets the size of collection by returning its length for array-like values or the number of enumerable string keyed properties for objects.
Parameters:
collection (Sized): Collection to inspect.Returns:
int: Collection size.Example:
from pydash import size
size([1, 2, 3])
# 3
size({'a': 1, 'b': 2})
# 2
size('hello')
# 5def some(collection: Iterable, predicate=None, from_index: int = 0) -> boolChecks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy.
Parameters:
collection (Iterable): Collection to iterate over.predicate (Callable, optional): Function invoked per iteration.from_index (int): Index to search from. Defaults to 0.Returns:
bool: True if any element passes the predicate check, else False.Example:
from pydash import some
some([1, 2, 3, 4], lambda x: x > 3)
# True
some([1, 2, 3, 4], lambda x: x > 5)
# Falsedef count_by(collection: Iterable, iteratee=None) -> Dict[Any, int]Creates a dictionary composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
Dict[Any, int]: New dictionary with counts.Example:
from pydash import count_by
count_by(['one', 'two', 'three'], len)
# {3: 2, 5: 1}
count_by([6.1, 4.2, 6.3], lambda x: int(x))
# {6: 2, 4: 1}def group_by(collection: Iterable[T], iteratee=None) -> Dict[Any, List[T]]Creates a dictionary composed of keys generated from the results of running each element of collection through iteratee. The order of grouped values is determined by the order they occur in collection.
Parameters:
collection (Iterable[T]): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
Dict[Any, List[T]]: New dictionary with grouped elements.Example:
from pydash import group_by
group_by(['one', 'two', 'three'], len)
# {3: ['one', 'two'], 5: ['three']}
group_by([6.1, 4.2, 6.3], lambda x: int(x))
# {6: [6.1, 6.3], 4: [4.2]}def key_by(collection: Iterable[T], iteratee=None) -> Dict[Any, T]Creates a dictionary composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the last element responsible for generating the key.
Parameters:
collection (Iterable[T]): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
Dict[Any, T]: New dictionary with keyed elements.Example:
from pydash import key_by
users = [{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Jane'}]
key_by(users, 'id')
# {1: {'id': 1, 'name': 'John'}, 2: {'id': 2, 'name': 'Jane'}}def nest(collection: Iterable[Any], *properties: Any) -> AnyReturns a nested dictionary where each key is an array of values from the corresponding properties.
Parameters:
collection (Iterable[Any]): Collection to nest.properties (*Any): Properties to group by.Returns:
Any: Nested dictionary structure.Example:
from pydash import nest
data = [
{'shape': 'square', 'color': 'red', 'used': 1, 'instances': 1},
{'shape': 'circle', 'color': 'red', 'used': 2, 'instances': 1}
]
nest(data, 'color', 'shape')def order_by(collection: Iterable, iteratees=None, orders=None, reverse=False) -> List[Any]Creates a list of elements sorted in ascending order by the results of running each element in a collection through each iteratee.
Parameters:
collection (Iterable): Collection to iterate over.iteratees (List[Callable], optional): Iteratees to sort by.orders (List[str], optional): Sort orders of iteratees ('asc' or 'desc').reverse (bool): Whether to reverse the sort order. Defaults to False.Returns:
List[Any]: New sorted list.Example:
from pydash import order_by
users = [
{'name': 'John', 'age': 30},
{'name': 'Jane', 'age': 25},
{'name': 'Bob', 'age': 30}
]
order_by(users, ['age', 'name'], ['asc', 'desc'])
# [{'name': 'Jane', 'age': 25}, {'name': 'John', 'age': 30}, {'name': 'Bob', 'age': 30}]def partition(collection: Iterable, predicate=None) -> List[List[Any]]Creates a list of two lists, the first of which contains elements predicate returns truthy for, the second of which contains elements predicate returns falsey for.
Parameters:
collection (Iterable): Collection to iterate over.predicate (Callable, optional): Function invoked per iteration.Returns:
List[List[Any]]: New list with partitioned elements.Example:
from pydash import partition
partition([1, 2, 3, 4], lambda x: x % 2 == 0)
# [[2, 4], [1, 3]]def sort_by(collection: Iterable, iteratee=None, reverse=False) -> List[Any]Creates a list of elements, sorted in ascending order by the results of running each element in a collection through each iteratee.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.reverse (bool): Whether to reverse the sort order. Defaults to False.Returns:
List[Any]: New sorted list.Example:
from pydash import sort_by
users = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]
sort_by(users, 'age')
# [{'name': 'Jane', 'age': 25}, {'name': 'John', 'age': 30}]
sort_by(['banana', 'apple', 'cherry'], len)
# ['apple', 'banana', 'cherry']def flat_map(collection: Iterable, iteratee=None) -> List[Any]Creates a flattened list of values by running each element in collection through iteratee and flattening the mapped results.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
List[Any]: New flattened list.Example:
from pydash import flat_map
flat_map([1, 2], lambda x: [x, x])
# [1, 1, 2, 2]
flat_map([{'a': [1, 2]}, {'a': [3, 4]}], 'a')
# [1, 2, 3, 4]def flat_map_deep(collection: Iterable, iteratee=None) -> List[Any]Like flat_map except that it recursively flattens the mapped results.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
List[Any]: New flattened list.Example:
from pydash import flat_map_deep
flat_map_deep([1, 2], lambda x: [[[x, x]]])
# [1, 1, 2, 2]def flat_map_depth(collection: Iterable, iteratee=None, depth: int = 1) -> List[Any]Like flat_map except that it recursively flattens the mapped results up to depth times.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.depth (int): Maximum recursion depth. Defaults to 1.Returns:
List[Any]: New flattened list.def for_each(collection: Iterable, iteratee=None) -> AnyIterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.Returns:
Any: collection.Example:
from pydash import for_each
result = []
for_each([1, 2, 3], lambda x: result.append(x * 2))
# result is now [2, 4, 6]def for_each_right(collection: Iterable, iteratee: Callable) -> AnyLike for_each except that it iterates over elements from right to left.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable): Function invoked per iteration.Returns:
Any: collection.def invoke_map(collection: Iterable, method_name: str, *args, **kwargs) -> List[Any]Invokes the method at method_name of each element in the collection, returning a list of the results of each invoked method.
Parameters:
collection (Iterable): Collection to iterate over.method_name (str): Name of method to invoke.args (*Any): Arguments to invoke the method with.kwargs (**Any): Keyword arguments to invoke the method with.Returns:
List[Any]: List of results.Example:
from pydash import invoke_map
invoke_map([[5, 1, 7], [3, 2, 1]], 'sort')
# [[1, 5, 7], [1, 2, 3]]def pluck(collection: Iterable[Any], path: str) -> List[Any]Retrieves the value of a specified property from all elements in the collection.
Parameters:
collection (Iterable[Any]): Collection to pluck.path (str): Property path to pluck.Returns:
List[Any]: New list of plucked values.Example:
from pydash import pluck
users = [{'name': 'John', 'age': 30}, {'name': 'Jane', 'age': 25}]
pluck(users, 'name')
# ['John', 'Jane']def reduce_(collection: Iterable, iteratee=None, accumulator=None) -> AnyReduces collection to a value which is the accumulated result of running each element in collection through iteratee, where each successive invocation is supplied the return value of the previous.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.accumulator (Any, optional): Initial value.Returns:
Any: Accumulated value.Example:
from pydash import reduce_
reduce_([1, 2, 3, 4], lambda acc, x: acc + x)
# 10
reduce_([1, 2, 3, 4], lambda acc, x: acc + x, 0)
# 10
# Reduce objects
reduce_({'a': 1, 'b': 2, 'c': 1}, lambda acc, val, key: acc + val, 0)
# 4def reduce_right(collection: Iterable, iteratee=None, accumulator=None) -> AnyLike reduce_ except that it iterates over elements from right to left.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.accumulator (Any, optional): Initial value.Returns:
Any: Accumulated value.Example:
from pydash import reduce_right
reduce_right([[0, 1], [2, 3], [4, 5]], lambda acc, x: acc + x, [])
# [4, 5, 2, 3, 0, 1]def reductions(collection: Iterable, iteratee=None, accumulator=None, from_right=False) -> List[Any]Like reduce_ except that it returns a list of each intermediate value in the reduction operation.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.accumulator (Any, optional): Initial value.from_right (bool): Whether to iterate from right to left. Defaults to False.Returns:
List[Any]: List of intermediate values.Example:
from pydash import reductions
reductions([1, 2, 3, 4], lambda acc, x: acc + x)
# [1, 3, 6, 10]
reductions([1, 2, 3, 4], lambda acc, x: acc + x, 0)
# [0, 1, 3, 6, 10]def reductions_right(collection: Iterable, iteratee=None, accumulator=None) -> List[Any]Like reductions except that it iterates over elements from right to left.
Parameters:
collection (Iterable): Collection to iterate over.iteratee (Callable, optional): Function invoked per iteration.accumulator (Any, optional): Initial value.Returns:
List[Any]: List of intermediate values.def reject(collection: Iterable, predicate=None) -> List[Any]The opposite of filter_. This method returns the elements of collection that predicate does not return truthy for.
Parameters:
collection (Iterable): Collection to iterate over.predicate (Callable, optional): Function invoked per iteration.Returns:
List[Any]: New filtered list.Example:
from pydash import reject
reject([1, 2, 3, 4], lambda x: x % 2 == 0)
# [1, 3]
# Using dict predicate
users = [{'name': 'John', 'active': True}, {'name': 'Jane', 'active': False}]
reject(users, {'active': True})
# [{'name': 'Jane', 'active': False}]def sample(collection: Sequence[T]) -> TGets a random element from collection.
Parameters:
collection (Sequence[T]): Collection to sample.Returns:
T: Random element.Example:
from pydash import sample
sample([1, 2, 3, 4])
# Random element from the arraydef sample_size(collection: Sequence[T], n: int = None) -> List[T]Gets n random elements at unique keys from collection up to the size of collection.
Parameters:
collection (Sequence[T]): Collection to sample.n (int, optional): Number of elements to sample.Returns:
List[T]: Random elements.Example:
from pydash import sample_size
sample_size([1, 2, 3, 4], 2)
# Random 2 elements from the arraydef shuffle(collection: Iterable[T]) -> List[T]Creates a list of shuffled values, using a version of the Fisher-Yates shuffle.
Parameters:
collection (Iterable[T]): Collection to shuffle.Returns:
List[T]: New shuffled list.Example:
from pydash import shuffle
shuffle([1, 2, 3, 4])
# Randomly shuffled version of the arrayThis Collections module provides comprehensive functionality for working with any iterable data structure, whether it's a list, dictionary, or custom iterable. The 31 functions cover all major collection processing patterns including filtering, mapping, reducing, grouping, and sampling operations.
Install with Tessl CLI
npx tessl i tessl/pypi-pydash