Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Work around KeyErrors solution in Clear category for The Flat Dictionary by new_hoschi
def flatten(dictionary):
solution={}
## in order to avoid any KeyError issues, we build a list of keys appearing
## in the dictionary
keys=list(dictionary.keys())
## idea: take the first key of your keylist,
## check whether its value is again a dict,
## if true: concatenate the first key with every low level-key to a new one
## and assign the value of the low level-key to this new key
## (example: {John:{Wayne:{the best:a,the greatest:b},Doe:c}}
## -> {John/Wayne:{the best:a,the greatest:b}, John/Doe:c} )
## (now the depth of nesting is reduced by one for this element)
## if false: this element is sufficiently flattened and can be appended to
## the solution (which will be the case for John/Doe in the next iteration)
##
## proceed until everything is superflat and there is no more nesting
while keys:
current_key=keys.pop(0)
current_value=dictionary.pop(current_key)
if type(current_value)==dict:
if not current_value:
solution[current_key]=""
for lowlevel_key in current_value.keys():
new_key=current_key + "/" + lowlevel_key
keys.append(new_key)
dictionary[new_key]=current_value[lowlevel_key]
else:
solution[current_key]=current_value
return solution
April 14, 2020
Comments: