pg.object_utils.flatten¶
Accessible via pg.object_utils.flatten
.
- flatten(src, flatten_complex_keys=True)[source]¶
Flattens a (maybe) hierarchical value into a depth-1 dict.
Example:
inputs = { 'a': { 'e': 1, 'f': [{ 'g': 2 }, { 'g[0]': 3 }], 'h': [], 'i.j': {}, }, 'b': 'hi', 'c': None } output = pg.object_utils.flatten(inputs) assert output == { 'a.e': 1, 'a.f[0].g': 2, 'a.f[1].g[0]': 3, 'a.h': [], 'a.i.j': {}, 'b': 'hi', 'c': None }
- Return type:
- Parameters:
src – source value to flatten.
flatten_complex_keys – if True, complex keys such as ‘x.y’ will be flattened
example (as 'x'.'y'. For) – {‘a’: {‘b.c’: 1}} will be flattened into {‘a.b.c’: 1} if this flag is on, otherwise it will be flattened as {‘a[b.c]’: 1}.
- Returns:
For primitive value types, src itself will be returned. For list and dict types, an 1-depth dict will be returned. For tuple, a tuple of the same length, with each element flattened will be returned. The order of keys in nested ordered dict will be preserved, Keys of different depth are joined into a string using “.” for dict properties and “[]” for list elements. For example, if src is:
{ "a": { "b": 4, "c": {"d": 10}, "e": [1, 2] 'f': [], 'g.h': {}, } }
then the output dict is:
{ "a.b": 4, "a.c.d": 10, "a.e[0]": 1, "a.e[1]": 2, "a.f": [], "a.g.h": {}, }
when flatten_complex_keys is True, and:
{ "a.b": 4, "a.c.d": 10, "a.e[0]": 1, "a.e[1]": 2, "a.f": [], "a.[g.h]": {}, }
when flatten_complex_keys is False.
- Raises:
ValueError – If any key from the nested dictionary contains “.”.