python3 多层/深层字典取值,不存在时返回默认值

python3 多层/深层字典取值,不存在时返回默认值

用到了reduce 函数实现
reduce函数的定义:
reduce(function, sequence [, initial] ) -> value
function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。
第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。

实现代码:

# -*- coding:utf-8 -*-

from functools import reduce


def get_from_dict(data_dict, map_list, defalut=None):

    def getitem(source, key):
        try:
            if isinstance(source, list):
                return source[int(key)]
            if isinstance(source, dict) and key not in source.keys():
                return defalut
        except IndexError:
            return defalut

        return source[key]

    if isinstance(map_list, str):
        map_list = map_list.split('.')

    return reduce(getitem, map_list, data_dict)


a = {'entry_data': {'hhh': 'hahah','ProfilePage': [{'graphql': 'hhhh'}, {'graphql2': 'hhhh2'}]}}
data_dict = 'entry_data.ProfilePage.0.graphql'  # or data_dict = ['entry_data', 'ProfilePage', 0]
res = get_from_dict(a, data_dict, 'hahahaaaa')

print(res)   # output: hhhh

各位可根据自己的情景修改此函数,如果有用的话希望留个言让我有点正反馈撒

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值