Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active October 14, 2024 21:01
Show Gist options
  • 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. This can be useful when writing to a format that requires a flat object/dictionary, such as CSV.
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