2
def solution(dict, output, ini):
    if (dict == None):
        return None
    else:
        for key in dict:
            if str(type(dict[key])) != str(type({})):
                print(key)
                output[ini + key] = dict[key]
            else:
                return solution(dict[key], output, ini + key + '.')
    return output

a = {
    'Key1': '1',
    'Key2': {
        'a': '2',
        'b': '3',
        'c': {
            'd': '3',
            'e': '1'
        }
    }
}
print(solution(a, {}, ""))

Hello I am trying to make a function that flattens nested dictionary.

For example a should print:

{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2', 'Key2.c.e': '1'}

But right now the code randomly gives me back the correct answer but from a range of 0-5 such as

{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2'},
{'Key2.b': '3', 'Key2.c.d': '3'}

I found out that if i get rid of the "return" in my else statement it would work but i am not sure why that is? Can anybody help me with it

Richard Luo
  • 37
  • 1
  • 2

2 Answers2

1

When you iterate over the keys in dict with for key in dict: it will return the keys in random order since elements in dictionaries aren't ordered. If Key1 is processed first it will be added to output and on the next iteration Key2 will be recursively processed. Now if the order is different and Key2 is processed first then return solution(dict[key],output,ini+key+'.') will cause the result to be returned before Key1 gets added to output. Same goes with nested elements within Key2. If you remove the return statement then all the keys will be processed no matter the iteration order and you'll get the expected output.

niemmi
  • 17,113
  • 7
  • 35
  • 42
0

as you put the result in output, you should not return at else,otherwise, the for loop will break, and the rest keys will be ignored.(just remove return, and it will do work)

Hooting
  • 1,681
  • 11
  • 20