美文网首页
python字典扁平化,递归实现和普通实现

python字典扁平化,递归实现和普通实现

作者: 小尤root | 来源:发表于2019-11-26 16:00 被阅读0次

    原字典
    in_data = {
    'jack': {
    'math': {'teacher': 'zhang', 'score': '75'},
    'english': {'teacher': 'xu', 'score': '90'},
    'height': '172'
    }
    }
    目标字典
    out_date={
    "jack_math_teacher": "zhang",
    "jack_math_score": "75",
    "jack_english_teacher": "xu",
    "jack_english_score": "90",
    "jack_height": "172"
    }
    普通for循环嵌套实现

    out_dict={}
    for ik,iv in in_data.items():
        for jk , jv in iv.items():
            if isinstance(jv,dict):
                for hk,hv in jv.items():
                    out_dict[ik+"_"+jk+"_"+hk]=hv
            else:
                out_dict[ik+"_"+jk] = jv
    print(out_date)
    

    递归实现

    def dict_to_tree(dict_o=None):
        if not dict_o or not isinstance(dict_o,dict):
            return
        def _dict_to_tree(dict_o,target=None,prefix=""):
            if target is None:
                target={}
            for k,value in dict_o.items():
                if isinstance(value,dict):
                    #递归调用
                    _dict_to_tree(value,target,prefix+k+"_")
                else:
                    target[prefix+k] = value
            return target
        return _dict_to_tree(dict_o)
    y_dict = dict_to_tree(in_data)
    print(y_dict)
    

    相关文章

      网友评论

          本文标题:python字典扁平化,递归实现和普通实现

          本文链接:https://www.haomeiwen.com/subject/gutywctx.html