列表索引必须是整数python嵌套字典 [英] list indices must be integers python nested dictionaries
问题描述
在python 3中,我需要一个函数来从嵌套键动态返回值.
In python 3, I need a function to dynamically return a value from a nested key.
nesteddict = {'a':'a1','b':'b1','c':{'cn':'cn1'}}
print(nesteddict['c']['cn']) #gives cn1
def nestedvalueget(keys):
print(nesteddict[keys])
nestedvalueget(['n']['cn'])
应如何编写nestedvalue?
How should nestedvalueget be written?
我不确定标题的用词是否正确,但是我不确定如何最好地描述这一点.
I'm not sure the title is properly phrased, but I'm not sure how else to best describe this.
推荐答案
如果要遍历字典,请使用循环:
If you want to traverse dictionaries, use a loop:
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)
然后使用以下任一版本:
then use either version as:
nestedvalueget('c', 'cn')
请注意,任何一个版本都采用可变数量的参数,以便让您将0个或多个键用作位置参数.
Note that either version takes a variable number of arguments to let you pas 0 or more keys as positional arguments.
演示:
>>> 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'
对其进行索引.列表索引只能是整数:
And to clarify your error message: You passed the expression ['n']['cn']
to your function call, which defines a list with one element (['n']
), which you then try to index with 'cn'
, a string. List indices can only be integers:
>>> ['n']['cn']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> ['n'][0]
'n'
这篇关于列表索引必须是整数python嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!