Skip to content

Instantly share code, notes, and snippets.

@tilboerner
Created July 14, 2020 18:10
Show Gist options
  • Save tilboerner/4738cda19af193516dc8b6cb196fc8de to your computer and use it in GitHub Desktop.
Save tilboerner/4738cda19af193516dc8b6cb196fc8de to your computer and use it in GitHub Desktop.
Python: flatten nested dict
def flatten(dd: dict, *, separator: str = '_') -> dict:
"""
Flatten nested dicts deeply.
Nested keys must be `str` and will be concatenated with a separator.
Example:
>>> flatten({'flat': 1, 'a': {'nested': {'key': 2}}})
{'flat': 1, 'a_nested_key': 2}
Note:
De-nesting can lead to new key collisions and data loss:
>>> flatten({'a': {'b': 111}, 'a_b': 2})
{'a_b': 2}
"""
return dict(_flatten_dict_items(dd.items(), separator))
def _flatten_dict_items(items, separator='_'):
for key, value in items:
if not isinstance(value, dict):
yield key, value
else:
yield from (
(key + separator + inner_key, inner_val)
for inner_key, inner_val in _flatten_dict_items(value.items(), separator)
)
@tilboerner
Copy link
Author

Interesting edge cases

Input Output
{'': {'': 1}} {'_': 1}
{'': {'a': {'': 2}}} {'_a_': 2}
({'a': {'': {'c': 3}}} {'a__c': 3}
{'a': {'b': {}}} {}
"NOT_A_DICT" AttributeError

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment