Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中获取字典中最里面的项_Python_Json_Loops_Dictionary_Yaml - Fatal编程技术网

如何在python中获取字典中最里面的项

如何在python中获取字典中最里面的项,python,json,loops,dictionary,yaml,Python,Json,Loops,Dictionary,Yaml,我用python将一个文件加载到字典中。假设它看起来像这样: {'dictionary': {'a': {'second_level': {'data': 'hello'}}, 'b': {'another_level': {'this_one_has_three_levels': {'data': 'hi'}}}}} ["dictionary>a>second_level>data>'hello'", "d

我用python将一个文件加载到字典中。假设它看起来像这样:

{'dictionary': {'a': {'second_level': {'data': 'hello'}},
                'b': {'another_level': {'this_one_has_three_levels': {'data': 'hi'}}}}}
["dictionary>a>second_level>data>'hello'", "dictionary>b>another_level>this_one_has_three_levels>data>'hi'"]
假设除了键“data”(因此我不能做
dictionary[a][data]
)之外,我不知道任何键,我如何编写一个函数,将整个dictionary作为输入并输出如下内容:

{'dictionary': {'a': {'second_level': {'data': 'hello'}},
                'b': {'another_level': {'this_one_has_three_levels': {'data': 'hi'}}}}}
["dictionary>a>second_level>data>'hello'", "dictionary>b>another_level>this_one_has_three_levels>data>'hi'"]
这需要将整个“路径”保存到最里面的元素“hello”和“hi”。
我想我需要在这里进行某种while循环,但我无法理解,如果事先不知道嵌套深度,递归方法通常是最简单的。下面是一个具有生成器功能的示例:

def get_data(dct, key):
    if key in dct:
        yield f"{key}>{dct[key]}"
    for k, v in dct.items():
        if isinstance(v, dict):
            for s in get_data(v, key):
                yield f"{k}>{s}"


>>> list(get_data(d, "data"))
['dictionary>a>second_level>data>hello', 
 'dictionary>b>another_level>this_one_has_three_levels>data>hi']

请从下一页重复和。“演示如何解决此编码问题?”与堆栈溢出无关。您必须诚实地尝试解决方案,然后询问有关实现的具体问题。堆栈溢出不用于替换现有教程和文档。这是一组:
{“hi”}
。你的字典真的有集合吗?我可能搞错了,我是从一个yaml文件中加载的,该文件中有
数据:“hi”
@请给我们看一本有效的词典。已将词典更改为有效词典