繁体   English   中英

嵌套的对象列表以递归方式获取所有键

[英]Nested list of objects get all keys recursively

我如何通过递归以下嵌套字典来获取所有键。

   DICTS = {
        'test/test': [
            {
                'test1/test1': [{'test3/test3': []}],
                'test2/test2': [],
                'test4/test4': []
            }
        ],
        'test8/test8': [
            {
                'test1/test5': [
                    {
                        'test6/test6': []
                    }
                ],
                'test7/test7': [],
                'test7/test7': []
            }
        ],
    }

例如,通过提供键 'test/test' 调用 function 并获取值列表:

my_recursive_func('test/test')

test1/test1
test3/test3
test2/test2
test4/test4

此解决方案仅对您的特定数据结构有效。

def my_recursive_func(data):
    result = []
    
    if isinstance(data, list):
        for datum in data:
            result.extend(my_recursive_func(datum))
            
    elif isinstance(data, dict):
        for key, value in data.items():
            result.append(key)
            result.extend(my_recursive_func(value))
            
    return result
my_recursive_func(DICTS['test/test'])
> ['test1/test1', 'test3/test3', 'test2/test2', 'test4/test4']

你基本上有两种情况:

当您的字典在另一本字典中时的情况 1

当你的字典在字典数组中时的情况 2

对于字典中的每个键,您将该键放入键数组中,并使用嵌套字典调用 function get_keys 如果你的嵌套字典是一个列表,你会为列表中的每一项返回get_keys()

def get_keys(dictionary):
    keys = []
    if isinstance(dictionary, list):
        for item in dictionary:
            keys.extend(get_keys(item))
    elif isinstance(dictionary, dict):
        for key in dictionary:
            keys.append(key)
            keys.extend(get_keys(dictionary[key]))
    return keys


print(get_keys(DICTS["test/test"]))

产出

['test1/test1', 'test3/test3', 'test2/test2', 'test4/test4']

此解决方案适用于任何给定结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM