Skip to content

Instantly share code, notes, and snippets.

@vallahor
Last active September 23, 2022 00:19
Show Gist options
  • Save vallahor/6acaf6f94530137cb12d1135133914dd to your computer and use it in GitHub Desktop.
Save vallahor/6acaf6f94530137cb12d1135133914dd to your computer and use it in GitHub Desktop.
flatten dict in python
def flatten_dict_aux(data, acc, get="kv"):
if isinstance(data, list):
for lst in data:
flatten_dict_aux(lst, acc, get)
elif isinstance(data, dict):
for k, v in data.items():
if isinstance(v, list) or isinstance(v, dict):
flatten_dict_aux(v, acc, get)
# delete this else to get all keys even keys with dict and arrays
else:
if get == "kv":
# Append a tuple with key and value
acc.append((k, v))
elif get == "k":
# Append only the key
acc.append(k)
elif get == "v":
# Append only the value
acc.append(v)
def flatten_dict(dict):
lst = []
flatten_dict_aux(dict, lst)
return lst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment