Created
January 4, 2024 15:19
-
-
Save grevych/89ff19764da136544b4fb716d54cd5ad to your computer and use it in GitHub Desktop.
Flatten python dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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