2017-06-29 502 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

请接受答案,如果这为你工作。 –