Skip to content

Instantly share code, notes, and snippets.

@TTy32
Created November 4, 2021 09:25
Show Gist options
  • Save TTy32/942bda78d2edbd9e6e9c42fbda0a18ea to your computer and use it in GitHub Desktop.
Save TTy32/942bda78d2edbd9e6e9c42fbda0a18ea to your computer and use it in GitHub Desktop.
A generic function to expand flat dicts
def expand_flatdict_to_tree(dict, sep = '_', to_lower = True):
tree = {}
for src, val in dict.items():
ref = tree
if to_lower:
src = src.lower()
for i, part in enumerate(src.split(sep)):
if part not in ref:
ref[part] = {}
if i == len(src.split(sep)) -1:
ref[part] = val # we cannot do ref = val after loop, as assignment to the ref itself will be passed by assignment
break
ref = ref[part] # update nest reference
return tree
flat_dict = {
'LOGLEVEL': 'INFO',
'DB_ENABLED': True,
'DB_CONNECTOR_HOST': 'localhost',
'DB_CONNECTOR_USER': 'root',
}
print (expand_flatdict_to_tree(flat_dict))
# {
# 'loglevel': 'INFO',
# 'db': {
# 'enabled': True,
# 'connector': {
# 'host': 'localhost',
# 'user': 'root'
# }
# }
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment