call a python class method recursively

江枫思渺然 提交于 2020-07-31 05:47:28

问题


I have a dictionary looking like this:

d ={'key1':{'key2':{'key11':{'key12':'value 13'}}},'key3':[{'key4':'value2', 'key5': 'value3'}]}

I want to get the value for 'key12' so I can do this:

d.get('key1').get('key2').get('key11').get('key12')

and it will return this:

'value 13'

if I had a list like this:

['key1', 'key2', 'key11', 'key12']

how could I call the get recursively over the above list to return the same result?


回答1:


You can use functools.reduce:

>>> from functools import reduce
>>> keys = ['key1', 'key2', 'key11', 'key12']
>>> reduce(dict.get, keys, d)
#or, reduce(lambda x,y:x.get(y), keys, d)
'value 13'

In python 3.8+ you can use the initial key in itertools.accumulate:

>>> from itertools import accumulate
>>> list(accumulate(keys, dict.get, initial=d))[-1]
'value 13'

I would still prefer functools.reduce, even though Guido doesn't




回答2:


d ={'key1':{'key2':{'key11':{'key12':'value 13'}}},'key3':[{'key4':'value2', 'key5': 'value3'}]}
ans = d.get('key1').get('key2').get('key11').get('key12')
print(ans)

key_list = ['key1', 'key2', 'key11', 'key12']
for key in key_list:
    d = d[key]

print(d)

Output:

value 13
value 13



回答3:


If you want to use a function:

def func(d, l):
    return func(d.get(l[0]), l[1:]) if l else d

Dict = {'key1': {'key2': {'key11': {'key12': 'value 13'}}}, 'key3': [{'key4': 'value2', 'key5': 'value3'}]}
List = ['key1', 'key2', 'key11', 'key12']

print(func(Dict, List))

Result:

value 13



回答4:


You can use the following function which gets the dictionary and the list and returns the requested value:

def func(a, b):
    for key in b:
        a = a.get(key)
        if a is None:
            raise ValueError('There is no such key as ' + str(key))
    return a

Usage:

a = {'key1':{'key2':{'key11':{'key12':'value 13'}}},'key3':[{'key4':'value2', 'key5': 'value3'}]}
b = ['key1', 'key2', 'key11', 'key12']

print(func(a, b))

Output:

value 13


来源:https://stackoverflow.com/questions/63088446/call-a-python-class-method-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!