Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
The Flat Dictionary solution in Uncategorized category for The Flat Dictionary by rbagg
def flatten(dictionary):
stack = [((), dictionary)]
result = {}
# With thanks to: https://py.checkio.org/forum/post/2762/the-flat-dictionary-task-doesnt-accept-solution/
# Iterate through stack until all values have been 'flattened'
while stack:
# Remove the 'right' value from the 'Stack' array
path, current = stack.pop()
# Iterate through the key value pairs of this value
for k,v in current.items():
# If the value is a 'dictionary' type with greater than one value
if isinstance(v, dict) and len(v) >= 1:
# Add the key value pair back to the 'Stack' array for
# later consideration
stack.append((path + (k,),v))
# If the value is not a dictionary, add it to the 'Result'
# dictionary and format per the instructions
else:
result["/".join((path + (k,)))] = str(v).replace('{}',"")
return result
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!')
June 18, 2018
Comments: