一个返回字典值的python函数

Rus*_*ell 1 python

我怎么能写一个函数,给定字典和键名,返回该值或False,例如:

d = {'a1' : 1, 'a2' : 2, 'a3' : {'b1' : 3, 'b2' : 4, 'b3' : {'c1' : 5}}}
get_dval(d, 'a1') => 1
get_dval(d, 'a3', 'b1') => 3
get_dval(d, 'a3', 'b3', 'c1') => 5
get_dval(d, 'a1', 'b2') => False
Run Code Online (Sandbox Code Playgroud)

Cra*_*sta 5

你想要的是get方法.即:

>>> my_dict = {'a': 2}
>>> my_dict.get('a', False)
2
>>> my_dict.get('b', False)
False
Run Code Online (Sandbox Code Playgroud)

如果您需要将此功能作为一项功能,您可以执行以下操作:

def get_dval(dict_, first_idx, *args):
    if not isinstance(dict_, dict):
        return False
    if len(args) == 0:
        return dict_.get(first_idx, False)
    else:
        if first_idx not in dict_:
            return False
        return get_dval(dict_[first_idx], *args)
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

def get_dval(dict_, *args):
    try:
        for idx in args:
            dict_ = dict_[idx]
    except:
        return False

    return dict_
Run Code Online (Sandbox Code Playgroud)