Python [练习题] :字典扁平化

习题:将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,赋值新字典。


原文地址:https://www.cnblogs.com/bolenzhang/p/8353233.html