Skip to content

Instantly share code, notes, and snippets.

@guissalustiano
Created November 21, 2021 04:27
Show Gist options
  • Save guissalustiano/165b337996ea1bcc9454d95d1381ec18 to your computer and use it in GitHub Desktop.
Save guissalustiano/165b337996ea1bcc9454d95d1381ec18 to your computer and use it in GitHub Desktop.
Exemplo medium Debugando aplicações em python
from typing import Dict, Any
def flatten_dict(root: Dict[str, Any], separator: str = '.') -> Dict[str, Any]:
"""
Tranforma dicionarios aninhados em um dicionario plano
Exemplo:
>>> flatten_dict({'a': 1, 'b': {'c': 2, 'd': 3}})
>>> {'a': 1, 'b.c': 2, 'b.d': 3}
"""
flatten_root = {}
for root_key, root_value in root.items():
if isinstance(root_value, dict):
flatten_item = flatten_dict(root_value)
for item_key, item_value in flatten_item.items():
flatten_root_key = separator.join([root_key, item_key])
flatten_root[flatten_root_key] = item_value
else:
flatten_root[root_key] = root_value
return flatten_root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment