2016-12-23 125 views
0
data = {"c":{"files":"s","d":{"files":["nothing"]}}} 
positions = ["c","d","files"] 

如何获得我在列表“职位”中的位置?我需要从列表中的“位置”这样的事情来获得:基于列表中的键检索嵌套字典中的值

data["c"]["d"]["files"] 

我还需要与列表,它是在那个位置工作。我已经尝试了一些,但我无法按照我想要的方式使用该列表。

def goto(data,positions): 
    temp = data 
    for i in positions: 
     temp = temp[i] 

有没有很酷的方式来做到这一点?

+0

显示应如何看待预期结果 – RomanPerekhrest

+1

这里没有关于JSON的信息...... –

回答

3

这是reduce的工作!

reduce(lambda a,b: a[b], positions, data) 

如果你使用Python 3,您需要导入reduce像这样:

from functools import reduce 

在Python 2,这是一个内置的功能,从而不需要进口。