Skip to content

Instantly share code, notes, and snippets.

@atheiman
Created November 9, 2023 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atheiman/4aadb570246c9c1a096b06837ace617e to your computer and use it in GitHub Desktop.
Save atheiman/4aadb570246c9c1a096b06837ace617e to your computer and use it in GitHub Desktop.
Convert python dictionary of many levels to single level dictionary with dot notation keys
def dict_dot_notation(d, path=[]):
d2 = {}
for k, v in d.items():
k_path = path + [str(k)]
k_formatted = ".".join(k_path)
if isinstance(v, dict):
# merge in dict with recursive call
d2 = {**d2, **dict_dot_notation(v, path=k_path)}
elif isinstance(v, list) or isinstance(v, tuple):
# handle list / tuple as comma separated strings
d2[k_formatted] = ",".join([str(i) for i in v])
else:
# force anything else to string representation
d2[k_formatted] = str(v)
return d2
d = {
'a': 'A',
'b': {
'c': 'C',
'd': {
'e': 'E',
'f': [0, 1, 2]
},
'g': [3, 4, 5],
'h': '',
'i': True
},
'j': False
}
import json
print(json.dumps(dict_dot_notation(d), indent=2))
# {
# "a": "A",
# "b.c": "C",
# "b.d.e": "E",
# "b.d.f": "0,1,2",
# "b.g": "3,4,5",
# "b.h": "",
# "b.i": "True",
# "j": "False"
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment