UniCoreFW

group_by()

Group array elements by the result of a function.

Implementation

Args: array: The array to group key_func: A function that returns a grouping key Returns: A dictionary with keys from key_func and arrays as values Raises: TypeError: If array is not iterable or key_func is not callable

Example

group_by([1, 2, 3], lambda x: x % 2)

Expected output: {0: [2], 1: [1, 3]}

Source Code

def group_by(array: List[T], key_func: Callable[[T], K]) -> dict: if not hasattr(array, "__iter__"): raise TypeError("The 'array' parameter must be iterable.") if not callable(key_func): raise TypeError("The 'key_func' parameter must be callable.") grouped = {} for item in array: try: key = key_func(item) grouped.setdefault(key, []).append(item) except Exception: # Handle exceptions securely # Optionally log the exception without exposing sensitive information continue # Skip elements that cause exceptions return grouped