![Python [练习题] :字典扁平化 Python [练习题] :字典扁平化](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
习题:将source字典扁平化,输出为 target 格式的字典。
source = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': {'g': 4}}}
target = {'a.b': 1, 'd.f.g': 4, 'd.e': 3, 'a.c': 2}
def func(src, targetkey='' ):
for k, v in src.items():
if isinstance(v, dict):
func(v, targetkey=targetkey + k + '.')
else:
target[targetkey + k] = v func(source)
print(target)
利用isinstance判断是否是字典,是的继续递归,否则合并key,赋值新字典。