字典扁平化
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))