Skip to main content
 首页 » 编程设计

python之一个返回字典值的python函数

2025年05月04日34zhenyulu

我如何编写一个函数,在给定字典和键名的情况下返回该值或 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 

请您参考如下方法:

您需要的是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_