Skip to content

Instantly share code, notes, and snippets.

@brainix
Last active February 9, 2021 01:52
Show Gist options
  • Save brainix/bf2b4aa01e3a8e435ede0a7b5065751c to your computer and use it in GitHub Desktop.
Save brainix/bf2b4aa01e3a8e435ede0a7b5065751c to your computer and use it in GitHub Desktop.
Flatten dict tech screen
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