I have a nested dict
(of dict
) and would like to be able, through a function, to access an element at any depth by giving the "path". In other words, access hello['world]['bonjour']
by calling myfunc(hello, 'world', 'bonjour')
(which I would define as def myfunc(mydict, *what)
).
I did not find anything built-in so I tried
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'))
This crashes with
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
I am not sure where the problem is (or - is there such a function so that I do not need to reinvent the wheel)
question from:
https://stackoverflow.com/questions/65902001/how-to-reduce-a-nested-dict 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…