'''标签:__,flat,target,map,python,prefix,dict,字典,扁平化 From: https://www.cnblogs.com/mengdie1978/p/16783240.html
source={'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}}}
target={}
def fun(sdict,dictkey=''):
for k,v in sdict.items():
if isinstance(v,dict):
fun(v,dictkey=dictkey+k+'.')
else:
target[dictkey+k]=v
fun(source)
print(target)
# {'a.b': 1, 'a.c': 2, 'd.e': 3, 'd.f.g': 4}
知识点
1.isinstance():判断v的类型是不是字典,如果不是就直接写入新字典;
2.递归(函数循环)
3.嵌套函数
'''
'''
sourt={'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}},'h':5}
dict_=dict()
def flatmap(sourt,prefix=''):
for i,j in sourt.items():
if isinstance(j,dict):
flatmap(j,prefix+i+'.')
else:
dict_[prefix+i]=j
return dict_
print(flatmap(sourt))
'''
'''
1.利用递归函数处理
2.每次判断k,v键值对的value,如果value为字典,那么继续递归处理,并且对新得到的key进行改造,
追加到末尾。如果value为整数,则停止递归。在新的字典上加上新的k,v对
3.最后返回新形成的字典
'''
'''
sourt={'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}},'h':5}
def flatmap(dis):
prefix=""
dict_={}
def innc(dis,prefix):
for i,j in dis.items():
if isinstance(j,dict):
innc(j,prefix+i+'.')
else:
dict_[prefix+i]=j
innc(dis,prefix)
return dict_
print(flatmap(sourt))
'''
'''
def flat_map(src,target=None,prefix=""):
if target is None:
target={}
for k,v in src.items():
if type(v) is dict:
flat_map(v,target,prefix+k+'.')
else:
target[prefix+k]=v
return target
if __name__=="__main__":
dict1={"a":{"b":{"c":4},"e":{"f":{"g":6}}}}
result_dict=flat_map(dict1)
print(result_dict)
'''
def flat_map_plus(src):
def _flat_map_plus(src, target=None,prefix=""):
if target is None:
target = {}
for k, v in src.items():
if type(v) is dict:
_flat_map_plus(v, target, prefix+k+".")
else:
target[prefix+k] = v
return target
target = _flat_map_plus(src)
return target
if __name__ == "__main__":
dict1 = {"a": {"b": {"c": 4}}, "e": {"f": {"g": 0}}}
new_result = flat_map_plus(dict1)
print(new_result)