Skip to content

Instantly share code, notes, and snippets.

@Cellebyte
Last active October 28, 2020 14:56
Show Gist options
  • Save Cellebyte/6a7c52b761310b9ed4d403ead8672bea to your computer and use it in GitHub Desktop.
Save Cellebyte/6a7c52b761310b9ed4d403ead8672bea to your computer and use it in GitHub Desktop.
Flatten a dict with comprehensions and a generator.
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