From e6166ca8276ef2143a343d7912ca02cfec3aed45 Mon Sep 17 00:00:00 2001 From: Mark McIntyre Date: Tue, 13 Jun 2023 11:29:40 -0400 Subject: [PATCH] added flatten utility --- python/flatten | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100755 python/flatten diff --git a/python/flatten b/python/flatten new file mode 100755 index 0000000..3fd1b38 --- /dev/null +++ b/python/flatten @@ -0,0 +1,32 @@ +def flatten(data_object, key_name=None): + # print('-' * 10) + # print(f"data_object = {data_object}, key_name = {key_name}") + + if type(data_object) == list: + for data_line in data_object: + # print(f"dl | data_line = {data_line}") + # print(f"dl | key_name = {key_name}") + # print(f":recursion") + flatten(data_line, key_name=key_name) + # print(":returned to the stack") + elif type(data_object) == dict: + for k, v in data_object.items(): + # print(f"dd | k, v = {k}, {v}") + # print(f"dd | key_name = {key_name}") + key_name = f"{key_name}.{k}" if key_name else k + # print(f"dd | key_name.k = {key_name}") + # print(f":recursion") + flatten(v, key_name=key_name) + + # print(":returned to the stack") + # print(f"dd | key_name = {key_name}") + key_name = ".".join(key_name.split('.')[:-1]) + # print("...back tracking key_name one level") + else: + print(f"--> {key_name}: {data_object}") if key_name else None + + # print("<< returning from this run") + # print('=' * 10) + + return +