Last active
October 28, 2020 14:56
-
-
Save Cellebyte/6a7c52b761310b9ed4d403ead8672bea to your computer and use it in GitHub Desktop.
Flatten a dict with comprehensions and a generator.
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
from typing import Any, Tuple, Generator | |
SEPARATOR = '.' | |
def dict_flatten( | |
d: dict, parent_key: str = "", sep: str = SEPARATOR | |
) -> Generator[Tuple[str, Any], None, None]: | |
for key, value in d.items(): | |
if isinstance(value, dict): | |
yield from dict_flatten(value, parent_key=f"{parent_key}{key}{sep}") | |
else: | |
yield (f"{parent_key}{key}", value) | |
if __name__ == '__main__': | |
data = {'apple':{'data':{'price':{'actual':5, 'discounted': 4}}}} | |
flat_dict = {key: value for key, value in dict_flatten(data)} | |
print(flat_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment