2017-06-29 204 views
-2

我想查找嵌套字典的元素。我想要的元素也是一個詞典。我嘗試這個功能,使用遞歸性:如何在Python中查找嵌套字典的元素(字典)

def find(key, dictionary): 
    for k, v in dictionary.items(): 
     if k == key: 
      yield v 
     elif isinstance(v, dict): 
      for result in find(key, v): 
       yield result 

這是我dictionnary:

nest_dict = {"a":{"b":{"c":{the dict i want} } } } 

我依次通過我的發電機:

for my_element in find('c', nest_dict): 
    print(my_element) 

的問題是,當我打印my_element ,它包含所有的內容,其中包含1個元素的nest_dict,而不僅僅是每個元素它的。

Thx。

PS:由於@Ashwini喬杜裏和@BoboDarph你的字典語法提到對不起,我的英語

+3

這甚至不是一個有效的字典語法。 –

+1

忽略示例dict和代碼的錯誤語法,獲取期望的嵌套字典的最簡單方法是對其應用3次。在你的簡單情況下,假設你想讓字典與關鍵字「c」關聯,你需要做的就是nested_dict.get('a')。get('b')。get('c') – BoboDarph

+0

輸出看起來正確我。你能告訴我們你得到的輸出和你期望得到的輸出嗎? –

回答

0

首先是無效做你問什麼可以做,以下:

nest_dict = {"a":{"b":{"c":'the dict i want' } } } 

print nest_dict['a']['b']['c'] 

輸出:

the dict i want 
+1

請接受答案,如果這爲你工作。 –