MCPcopy
hub / github.com/langroid/langroid / nested_dict_from_flat

Function nested_dict_from_flat

langroid/utils/pydantic_utils.py:319–348  ·  view source on GitHub ↗

Given a flattened version of a nested dict, reconstruct the nested dict. Field names in the flattened dict are assumed to be of the form "field1__field2__field3", going from top level down. Args: flat_data (Dict[str, Any]): The flattened dict. sub_dict (str, optiona

(
    flat_data: Dict[str, Any],
    sub_dict: str = "",
)

Source from the content-addressed store, hash-verified

317
318
319def nested_dict_from_flat(
320 flat_data: Dict[str, Any],
321 sub_dict: str = "",
322) -> Dict[str, Any]:
323 """
324 Given a flattened version of a nested dict, reconstruct the nested dict.
325 Field names in the flattened dict are assumed to be of the form
326 "field1__field2__field3", going from top level down.
327
328 Args:
329 flat_data (Dict[str, Any]): The flattened dict.
330 sub_dict (str, optional): The name of the sub-dict to extract from the
331 flattened dict. Defaults to "" (extract the whole dict).
332
333 Returns:
334 Dict[str, Any]: The nested dict.
335
336 """
337 nested_data: Dict[str, Any] = {}
338 for key, value in flat_data.items():
339 if sub_dict != "" and not key.startswith(sub_dict + "__"):
340 continue
341 keys = key.split("__")
342 d = nested_data
343 for k in keys[:-1]:
344 d = d.setdefault(k, {})
345 d[keys[-1]] = value
346 if sub_dict != "": # e.g. "payload"
347 nested_data = nested_data[sub_dict]
348 return nested_data
349
350
351def pydantic_obj_from_flat_dict(

Callers 1

Calls 1

splitMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…