Returns a dictionary with the average value of each key in the input list of dictionaries.
(list_of_dicts: list)
| 63 | |
| 64 | |
| 65 | def key_average(list_of_dicts: list) -> Dict[str, Any]: |
| 66 | """ |
| 67 | Returns a dictionary with the average value of each key in the input list of dictionaries. |
| 68 | """ |
| 69 | _nested_dict_keys = set() |
| 70 | for d in list_of_dicts: |
| 71 | _nested_dict_keys.update(traverse_nested_dict_keys(d)) |
| 72 | _nested_dict_keys = sorted(_nested_dict_keys) |
| 73 | result = {} |
| 74 | for k in _nested_dict_keys: |
| 75 | values = [] |
| 76 | for d in list_of_dicts: |
| 77 | v = get_nested_dict(d, k) |
| 78 | if v is not None and not math.isnan(v): |
| 79 | values.append(v) |
| 80 | avg = sum(values) / len(values) if values else float('nan') |
| 81 | set_nested_dict(result, k, avg) |
| 82 | return result |
| 83 | |
| 84 | |
| 85 | def flatten_nested_dict(d: Dict[str, Any], parent_key: Tuple[str, ...] = None) -> Dict[Tuple[str, ...], Any]: |
nothing calls this directly
no test coverage detected