defflatten(d): def_flatten(d, prefix=None): for k,v in d.items(): full_key = k if prefix isNoneelse prefix + '.' + k ifisinstance(v, dict): # yield from 可以逐个返回递归调用中的结果 yieldfrom _flatten(v, full_key) else: yield full_key,v return {k:v for k,v in _flatten(d)}
合并迭代返回值
1 2 3 4 5 6 7 8 9 10 11
defflatten(d, prefix=None): items = {} for k,v in d.items(): full_key = k if prefix isNoneelse prefix + '.' + k ifisinstance(v, dict): # 通过 dict 的 update 方法合并子递归返回内容 sub_items = flatten(v, full_key) items.update(sub_items) else: items[full_key] = v return items