Skip to content

Instantly share code, notes, and snippets.

@SteadBytes
Created February 28, 2019 15:25
Show Gist options
  • Save SteadBytes/b58dad64b73ddf999730e483d7efc579 to your computer and use it in GitHub Desktop.
Save SteadBytes/b58dad64b73ddf999730e483d7efc579 to your computer and use it in GitHub Desktop.
Transform dot-notation keys into nested dictionary
def dot2dict(a):
dict_tree = lambda: defaultdict(dict_tree)
output = dict_tree()
for k, v in a.items():
path = k.split(".")
target = reduce(lambda d, k: d[k], path[:-1], output)
target[path[-1]] = v
return output
if __name__ == "__main__":
print(
dot2dict(
{
"event.name": "progress",
"event.status": "complete",
"event.user.name": "bob",
"event.user.email": "bob@gmail.com",
}
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment