我想定义一个小包装函数,它使用某种“路径”来访问不同级别的嵌套字典:
D = {'key1': valueA,
'key2': {'key21': valueB,
{'key22': valueC}
在这个简单的例子中,我想编写一个函数作为参数,例如,像
这样的元组dict_path = ('key2', 'key22')
>>>nested_getter(dict_path)
valueC
答案 0 :(得分:4)
D = {'key1': valueA,
'key2': {'key21': valueB,
'key22': valueC}}
def nested_getter(root, path):
for elem in path:
root = root[elem]
return root
你可以这样做:
>>> nested_getter(D, ('key2', 'key22'))
3
答案 1 :(得分:4)
def nested_getter(d, keys):
return reduce(dict.get, keys, d)