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.

Revisions

  1. grevych created this gist Jan 4, 2024.
    23 changes: 23 additions & 0 deletions flatten_dict.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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