python嵌套列表索引,列表索引必须是整数python嵌套字典

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'])

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

from functools import reduce

from operator import getitem

def nestedvalueget(*keys):

return reduce(getitem, keys, nesteddict)

then use either version as:

nestedvalueget('c', 'cn')

Note that either version takes a variable number of arguments to let you pas 0 or more keys as positional arguments.

Demos:

>>> 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'

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 "", line 1, in

TypeError: list indices must be integers, not str

>>> ['n'][0]

'n'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值