key_by()
Creates an object composed of keys generated from the results of running each element of the given collection through the given iteratee.
Implementation
Args: collection: The collection to process. Should be a list of dictionaries. iteratee: The function to run each element of the collection through. Can be a string (in which case the value of the given key is used) or a callable. Returns: An object with the results of running the iteratee on each element of the collection as keys, and the element of the collection as the values.
Example
key_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], 'a')
Expected output: {1: {'a': 1, 'b': 2}, 3: {'a': 3, 'b': 4}}
Source Code
def key_by(
collection: List[Dict[Any, Any]], iteratee: Union[str, Callable]
) -> Dict[Any, Dict[Any, Any]]:
if isinstance(iteratee, str):
def fn(x):
return x.get(iteratee)
else:
fn = iteratee
out: Dict[Any, Any] = {}
for x in collection:
out[fn(x)] = x
return out