源字典

source = {'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}}}

转换目标字典

target = {'a.b': 1, 'a.c': 2, 'd.e': 3, 'd.f.g': 4}

实现方式一

#扁平化字典
#

source = {'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}}}
target={}

def fn(source, string=''):
    for key,value in source.items():
        if isinstance(value, dict):
            fn(value, string=string+key+'.')
        else:
            target[string+key] = value

fn(source)
print(target)
# {'a.b': 1, 'a.c': 2, 'd.e': 3, 'd.f.g': 4}

实现方式二

source = {'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}}}

def fn(source, target=None, prefix=''):
    if target == None:
        target = dict()
    for key, value in source.items():
        if isinstance(value, dict):
            fn(value, target, prefix=prefix+key+'.')    # prefix 只是被传参进去,并未对入口出的prefix做修改
        else:
            target[prefix+key] = value
    return target

target = fn(source)
print(target)
Last modification:June 15th, 2020 at 04:13 pm
If you think my article is useful to you, please feel free to appreciate