<分区> 分区>
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, {}, ""))
你好,我正在尝试制作一个可以压平嵌套字典的函数。
例如一个应该打印:
{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2', 'Key2.c.e': '1'}
但现在代码随机给我返回正确答案,但范围是 0-5,例如
{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2'},
{'Key2.b': '3', 'Key2.c.d': '3'}
我发现,如果我去掉 else 语句中的“return”,它会起作用,但我不确定为什么会这样?谁能帮我一下
