python字典多层嵌套取指定key值

最近在用Python做接口测试,经常要解析接口响应的body,其loads后经常出现字典多层嵌套,而我们想要的往往是某个key的值,我的思路是这样的,先判断key在不在最外层字典的keys中,若在直接取值,若不在,说明在value对应的嵌套字典中(当然也有可能不存在,但是不影响,只是取不到值而已),于是遍历最外层字典的value,进一步判断value,若是字典,接着循环,若是列表,遍历取值,再判断,这样可以定义两个函数相互调用就行了,

def get_value_from_json(key, tdict, tem_list):
    """
    从Json中获取key值,
    :param key:
    :param tdict:
    :param tem_list:
    :return:
    """
    if not isinstance(tdict, dict):
        return tdict + "is not dict"
    elif key in tdict.keys():
        tem_list.append(tdict[key])
    else:
        for value in tdict.values():
            if isinstance(value, dict):
                get_value_from_json(key, value, tem_list)
            elif isinstance(value, (list, tuple)):
                _get_value(key, value, tem_list)
    return tem_list


def _get_value(key, tdict, tem_list):
    """

    :param key:
    :param tdict:
    :param tem_list:
    :return:
    """
    for value in tdict:
        if isinstance(value, (list, tuple)):
            _get_value(tdict)
        elif isinstance(value, dict):
            get_value_from_json(key, value, tem_list)

 

转载于:https://my.oschina.net/u/4188927/blog/3094744

你可能感兴趣的:(python字典多层嵌套取指定key值)