>>> d = {1: {2: {3: {4: {5: 'a'}}}}}
>>> def get_item(d,*keys):
... for i,j in enumerate(keys):
... item = d[j]
... if isinstance(item, dict):
... return get_item(item,*keys[i+1:])
... return item
或者使用next内的生成器表达式:
^{pr2}$
或者,作为一种更为python的方法,您可以将键的迭代器传递给函数:
def get_item(d,keys):
try:
item = d[next(keys)]
except KeyError:
raise Exception("There is a mismatch within your keys")
if isinstance(item, dict):
return get_item(item,keys)
return item
是的,为了拒绝引发语法错误,您需要对新行进行转义。但作为另一种替代方法,您可以使用递归函数从嵌套字典中获取值:
或者使用
^{pr2}$next
内的生成器表达式:或者,作为一种更为python的方法,您可以将键的迭代器传递给函数:
相关问题 更多 >
编程相关推荐