1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
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,(list,tuple,set,dict)): flatmap(v,prefix=prefix+k+'.')
else: target[prefix+k] = v flatmap(source) print(target)
输出: {'a.b': 1, 'a.c': 2, 'd.e': 3, 'd.f.g': 4}
- 一般这种函数都会生成一个新的字典,因此改造一下dest字典可以由内部创建,也可以由外部提供 source = {'a':{'b':1,'c':2},'d':{'e':3,'f':{'g':4}}}
def flatmap(src,dest=None,prefix=''): if dest == None: dest = {} for k,v in src.items(): if isinstance(v,(list,tuple,set,dict)): flatmap(v,dest,prefix=prefix+k+'.') else: dest[prefix+k] = v return dest
print(flatmap(source)) 输出: {'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 flatmap(src): def _flatmap(src,dest=None,prefix=''): for k,v in src.items(): key = prefix + k
if isinstance(v,(list,tuple,set,dict)): _flatmap(v,dest,key + '.') else: dest[key] = v dest = {} _flatmap(src,dest) return dest
print(flatmap(source)) 输出: {'a.b': 1, 'a.c': 2, 'd.e': 3, 'd.f.g': 4}
|