Last active
February 9, 2021 01:52
-
-
Save brainix/bf2b4aa01e3a8e435ede0a7b5065751c to your computer and use it in GitHub Desktop.
Flatten dict tech screen
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
import collections | |
def flatten(dict_, *, separator='.', raise_on_collision=True): | |
flattened = {} | |
for key, value in dict_.items(): | |
if isinstance(value, collections.abc.Mapping): | |
tmp_dict = flatten(value) | |
for tmp_key, tmp_value in tmp_dict.items(): | |
tmp_key = separator.join((key, tmp_key)) | |
if raise_on_collision and tmp_key in flattened: | |
raise ValueError(f"collision on key '{tmp_key}'") | |
flattened[tmp_key] = tmp_value | |
else: | |
if raise_on_collision and key in flattened: | |
raise ValueError(f"collision on key '{key}'") | |
flattened[key] = value | |
return flattened | |
dict_ = { | |
'a': 5, | |
'b': 6, | |
'c': { | |
'f': 9, | |
'g': { | |
'm': 17, | |
'n': 3, | |
}, | |
}, | |
} | |
print(flatten(dict_)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment