Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
if it works, its ok solution in Uncategorized category for The Flat Dictionary by danersow
def flat(dictionary):
res_dict = {}
for entry in dictionary:
if type(dictionary[entry]) == dict:
if dictionary[entry] == {}:
res_dict[entry] = ""
for i in dictionary[entry]:
res_dict[entry+"/"+i] = dictionary[entry][i]
else:
res_dict[entry] = dictionary[entry]
return(res_dict)
def flatten(dictionary):
while True:
dictionary = flat(dictionary)
end = True
for d in dictionary:
if type(dictionary[d]) == dict:
end = False
if end == False:
continue
return 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. 15, 2020
Comments: