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