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
您需要的是
get
方法。即:如果您需要将此作为一个函数,您可以执行以下操作:
或者你可以这样做:
非递归函数:
相关问题 更多 >
编程相关推荐