标签:ict upd dict pre lis nbsp info 扁平化 else
source={‘a‘:{‘b‘:1,‘c‘:2},‘d‘:{‘e‘:3,‘f‘:{‘g‘:4}}}
target={}
def flatmap(src,prefix=‘‘):
for k,v in src.items():
if isinstance(v,(dict,)):
flatmap(v,prefix=prefix+k+‘~‘)
else:
target.setdefault(prefix+k,v)
flatmap(source)
print(target)
def flatmap(src,target=None,prefix=‘‘):
if target is None:
target={}
for k,v in src.items():
if isinstance(v,(list,tuple,set,dict)):
flatmap(v,target,prefix=prefix+k+‘~‘)
else:
target.update(((prefix+k,v),))
return target
print(flatmap(source))
def flatmap(src):
def _flatmap(src,dst=None,prefix=‘‘):
if dst is None:
dst={}
for k,v in src.items():
key=prefix+k
if isinstance(v,(tuple,list,set,dict)):
_flatmap(v,dst,key+‘~‘)
else:
dst.update(((key,v),))
return dst
return _flatmap(src)
print(flatmap(source))
标签:ict upd dict pre lis nbsp info 扁平化 else
原文地址:https://www.cnblogs.com/dissipate/p/13619671.html