Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursive dict.update() solution in Clear category for The Flat Dictionary by 2010min0ru
def flatten(dictionary, key_string=""):
"""Flatten nested dictionaries with chaining keys into path."""
flat_dictionary = {}
for key, value in dictionary.items():
new_key = f'{key_string}/{key}' if key_string else key
if not value:
flat_dictionary[new_key] = ""
elif isinstance(value, str):
flat_dictionary[new_key] = value
else:
flat_dictionary.update(flatten(value, new_key))
return flat_dictionary
if __name__ == '__main__':
test_input = {"key": {"deeper": {"more": {"enough": "value"}}}}
print(' Input: {}'.format(test_input))
print('Output: {}'.format(flatten(test_input)))
#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"}
print('You all set. Click "Check" now!')
Oct. 22, 2020