Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for The Flat Dictionary by book1978
def flatten(dictionary, path=''):
n = {}
for k, z in dictionary.items():
p = (path + '/' + k).lstrip('/')
n.update(flatten(z, p) if isinstance(z, dict) and z else {p: ['', z][bool(z)]})
return n
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
assert flatten(
{"key": {"deeper": {"more": {"enough": "value"}}}}
) == {"key/deeper/more/enough": "value"}, "Nested"
assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
assert flatten({"name": {
"first": "One",
"last": "Drone"},
"job": "scout",
"recent": {},
"additional": {
"place": {
"zone": "1",
"cell": "2"}}}
) == {"name/first": "One",
"name/last": "Drone",
"job": "scout",
"recent": "",
"additional/place/zone": "1",
"additional/place/cell": "2"}
March 13, 2023