返回字典值的python函数

2024-06-26 14:23:31 发布

您现在位置: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

Tags: 函数falsea2get字典a1b2a3
2条回答

您需要的是get方法。即:

>>> my_dict = {'a': 2}
>>> my_dict.get('a', False)
2
>>> my_dict.get('b', False)
False

如果您需要将此作为一个函数,您可以执行以下操作:

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)

或者你可以这样做:

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

    return dict_

非递归函数:

def get_dval(value, *args):
    args = list(args)
    while args:
        try:
            value = value.get(args.pop(0), False)
        except Exception:
            # deal with non-dict `dict_` which not hasattr `__getitem__`
            value = False
            break
    return value

相关问题 更多 >