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": ""}

  • What is hidden in the stack variable? - m9_psy
  • @ m9_psy stack = [((), dictionary)] - Sergey Rodin

3 answers 3

 def flatten(dt: dict): for k in dt: yield k dk = dt[k] if isinstance(dk, dict): if dk: yield from flatten(dk) else: yield "" else: yield dk dts = {"key": {"deeper": {"more": {}}}, "key2": {"deeper2": {"more2": '123'}}} for k in dts: b = list(flatten({k: dts[k]})) print({'/'.join(b[:-1]): b[-1]}) 

Out:

 {'key/deeper/more': ''} {'key2/deeper2/more2': '123'} 

    I got this solution:

     def flatten(dictionary): stack = list(dictionary.items()) result = {} while stack: path, current = stack.pop() if current == {}: result[path] = "" for k, v in current.items(): if isinstance(v, dict): stack.append(("/".join([path, k]), v)) else: result["/".join([path, k])] = v return result 

    Background data question:

     print (flatten({"key": {"deeper": {"more": {}}}})) {'key/deeper/more': ''} 

    More complex structure:

     print (flatten({"key": {"deeper": {"more": {}}, "deep2": "more2"}, "key2": {"deep3":"more3"}})) {'key2/deep3': 'more3', 'key/deeper/more': '', 'key/deep2': 'more2'} 

      When I solved this problem on checkio, I did it like this:

       def flatten(dictionary): stack = [((), dictionary)] result = {} while stack: path, current = stack.pop() for k, v in current.items(): if v == {}: v = '' if isinstance(v, dict): stack.append((path + (k,), v)) else: result["/".join((path + (k,)))] = v return result 
      • one
        Well, then tick off, the answer that you liked more, and you can still vote (the triangle looks up);) - privod