A dictionary is given, in which strings are used as keys, and strings or dictionaries as values. It is necessary to make this dictionary “flat”, but keep the structure in the keys.
The result will be a dictionary without nested dictionaries. Keys must contain a path composed of parent keys from the initial dictionary, separated by
/
. If the key value is an empty dictionary, then it must be replaced with an empty string (""
).
I don’t understand how to change this code:
def flatten(dictionary): stack = result = {} while stack: path, current = stack.pop() for k, v in current.items(): if isinstance(v, dict): stack.append((path + (k,), v)) else: result = v return result
Enter:
print (flatten({"key": {"deeper": {"more": {}}}}))
Conclusion: {}
It should be: {"key/deeper/more": ""}
stack
variable? - m9_psy