UniCoreFW

nest()

Groups a list of dictionaries into a nested dictionary based on the specified keys.

Implementation

Args: collection: A list of dictionaries to be nested. keys: A list of keys to nest the dictionaries by. The order of keys determines the hierarchy of the nesting. Returns: A nested dictionary where each level corresponds to a key in the keys list, and the final level contains lists of dictionaries from the collection that share the same key values.

Example

collection = [ {'type': 'fruit', 'name': 'apple', 'color': 'red'}, {'type': 'fruit', 'name': 'banana', 'color': 'yellow'}, {'type': 'vegetable', 'name': 'carrot', 'color': 'orange'} ] keys = ['type', 'color'] nest(collection, keys)

Expected output: { 'fruit': { 'red': [{'type': 'fruit', 'name': 'apple', 'color': 'red'}], 'yellow': [{'type': 'fruit', 'name': 'banana', 'color': 'yellow'}], }, 'vegetable': { 'orange': [{'type': 'vegetable', 'name': 'carrot', 'color': 'orange'}] } }

Source Code

def nest(collection: List[Dict[Any, Any]], keys: List[str]) -> Dict[Any, Any]: out: Dict[Any, Any] = {} for x in collection: curr = out for i, k in enumerate(keys): val = x.get(k) if i == len(keys) - 1: curr.setdefault(val, []).append(x) else: curr = curr.setdefault(val, {}) return out