"""Perpetual Inventory helpers.""" def dict_from_collection(coll, key): """Return a dict indexed by unique values of a specified in a collection. Args: coll (list): list of dicts key (str): key Returns: _dict (dict): dict keyed by unique values from collection. """ _dict = {} for i, d in enumerate(coll): curr_dict = d if curr_dict[key] not in _dict.keys(): _dict[curr_dict[key]] = [curr_dict] else: _dict[curr_dict[key]].append(curr_dict) return _dict def min_dict(_d, user_key): """Return dict where user_key matches the min value.""" _dict = {} for key, value in _d.items(): _dict[key] = dict(min(value, key=lambda x: x[user_key])) return _dict def max_dict(_d, user_key): """Return dict where user_key matches the max value.""" _dict = {} for key, value in _d.items(): _dict[key] = dict(max(value, key=lambda x: x[user_key])) return _dict def sum_key_in_collection(coll, key): """Return a sum for a key in a collection.""" if not coll: return 0 return sum([dict(item).get(key, 0) or 0 for item in coll])