Skip to content

Instantly share code, notes, and snippets.

@grevych
Created January 4, 2024 15:19
Show Gist options
  • Save grevych/89ff19764da136544b4fb716d54cd5ad to your computer and use it in GitHub Desktop.
Save grevych/89ff19764da136544b4fb716d54cd5ad to your computer and use it in GitHub Desktop.
Flatten python dictionary
def flatten_dict(d: any):
if not isinstance(d, dict):
return []
flat_d = _flatten_dict(d)
for index in range(len(flat_d)):
flat_d[index] = tuple(flat_d[index])
return flat_d
def _flatten_dict(d: any):
if not isinstance(d, dict):
return [[str(d)]]
paths = []
for key in d.keys():
value = d[key]
for inner_path in _flatten_dict(value):
paths.append([key] + inner_path)
return paths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment