如果要遍历字典,请使用循环:
def nestedvalueget(*keys):
ob = nesteddict
for key in keys:
ob = ob[key]
return ob
或使用functools.reduce()
:
from functools import reduce
from operator import getitem
def nestedvalueget(*keys):
return reduce(getitem, keys, nesteddict)
然后将任一版本用作:
nestedvalueget('c', 'cn')
请注意,任何一个版本都采用可变数量的参数来让您传递 0 个或多个键作为位置参数。
演示:
>>> nesteddict = {'a':'a1','b':'b1','c':{'cn':'cn1'}}
>>> def nestedvalueget(*keys):
... ob = nesteddict
... for key in keys:
... ob = ob[key]
... return ob
...
>>> nestedvalueget('c', 'cn')
'cn1'
>>> from functools import reduce
>>> from operator import getitem
>>> def nestedvalueget(*keys):
... return reduce(getitem, keys, nesteddict)
...
>>> nestedvalueget('c', 'cn')
'cn1'
并澄清您的错误消息:您将表达式传递['n']['cn']
给您的函数调用,该函数调用定义了一个包含一个元素 ( ['n']
) 的列表,然后您尝试使用'cn'
一个字符串对其进行索引。列表索引只能是整数:
>>> ['n']['cn']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> ['n'][0]
'n'