Created
July 14, 2020 18:10
-
-
Save tilboerner/4738cda19af193516dc8b6cb196fc8de to your computer and use it in GitHub Desktop.
Python: 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 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) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting edge cases
{'': {'': 1}}
{'_': 1}
{'': {'a': {'': 2}}}
{'_a_': 2}
({'a': {'': {'c': 3}}}
{'a__c': 3}
{'a': {'b': {}}}
{}
"NOT_A_DICT"
AttributeError