Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
My "flat dictionary" program solution in Clear category for The Flat Dictionary by Phil15
def flatten(dictionary):
"""Flatten a dictionary.
If the dict is already flat, there is nothing to do.
For flatten a dict, we look each value of the dictionary.
If the value is a string, we copy it in D.
If the value is a empty dict, this must be replaced by a empty string '' in D.
Else the value is a non empty dict, we flatten this dict value before integrate it into D.
"""
if all(type(v) is str for v in dictionary.values()):
return dictionary
D = {}
for key in dictionary.keys():
if type(dictionary[key]) is str:
D[key] = dictionary[key]
elif len(dictionary[key])==0:
D[key] = ''
else:
E = flatten(dictionary[key])
for keyE in E:
D[key+'/'+keyE] = E[keyE]
return D
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!')
Feb. 27, 2018
Comments: