Last active
March 7, 2024 03:05
-
-
Save pranithan-kang/7ec2dde02a5bafca41505b3678aed856 to your computer and use it in GitHub Desktop.
deep flatten nested dict
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 deep_flatten(data: dict, flatten_result: dict = {}, parent_key: str = ""): | |
for key, value in data.items(): | |
target_key = f"{parent_key}.{key}" if parent_key else key | |
if isinstance(value, dict): | |
deep_flatten(value, flatten_result, target_key) | |
else: | |
flatten_result[target_key] = value | |
return flatten_result | |
assert deep_flatten( | |
{ | |
"a": "1", | |
"b": { | |
"b1": "testing_b1", | |
"b2": 123, | |
"b3": {"b1_1": 1, "b1_2": 2, "b1_3": "test-inner-b1_3"}, | |
}, | |
"c": {"c1": [1, 2, 3], "c2": 0, "c3": None}, | |
}) == { | |
"a": "1", | |
"b.b1": "testing_b1", | |
"b.b2": 123, | |
"b.b3.b1_1": 1, | |
"b.b3.b1_2": 2, | |
"b.b3.b1_3": "test-inner-b1_3", | |
"c.c1": [1, 2, 3], | |
"c.c2": 0, | |
"c.c3": None, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment