2016-12-23 121 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,這是一個內置的功能,從而不需要進口。