【发布时间】:2021-01-26 13:10:51
【问题描述】:
我有一个嵌套的dict(dict),并希望能够通过一个函数,通过给出“路径”来访问任何深度的元素。换句话说,通过调用myfunc(hello, 'world', 'bonjour')(我将其定义为def myfunc(mydict, *what))来访问hello['world]['bonjour']。
我没有找到任何内置的,所以我尝试了
import functools
class State:
def __init__(self):
self.data = {
"a": 1,
"b": {
"c": 10
}
}
def get(self, *what):
return functools.reduce(lambda x: self.data[x], what)
state = State()
print(state.get('a', 'b'))
这会崩溃
Traceback (most recent call last):
File "C:/Users/yop/AppData/Roaming/JetBrains/PyCharm2020.3/scratches/scratch_4.py", line 19, in <module>
print(state.get('a', 'b'))
File "C:/Users/yop/AppData/Roaming/JetBrains/PyCharm2020.3/scratches/scratch_4.py", line 15, in get
a = functools.reduce(lambda x: self.data[x], what)
TypeError: <lambda>() takes 1 positional argument but 2 were given
我不确定问题出在哪里(或者 - 是否有这样的功能,所以我不需要重新发明轮子)
【问题讨论】:
标签: python dictionary lambda