Loading... ###源字典 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) 最后修改:2020 年 06 月 15 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 0 如果觉得我的文章对你有用,请随意赞赏