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 Molot
def flatten(dictionary):
def flat_aligning(key_, dict_):
# get flatten dict for each iteration
if isinstance(dict_, dict) and dict_:
return {key_+'/'+k: v for k,v in dict_.items()}
return {key_: ''} if dict_ == {} else {key_: dict_}
new_dict = {}
while not all(map(lambda x: isinstance(x, str), dictionary.values())):
for k,v in dictionary.items(): new_dict.update(flat_aligning(k,v))
dictionary, new_dict = new_dict, {}
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!')
July 18, 2018