如何通过递归下面的嵌套dict来获得所有的键。
DICTS = {
'test/test': [
{
'test1/test1': [{'test3/test3': []}],
'test2/test2': [],
'test4/test4': []
}
],
'test8/test8': [
{
'test1/test5': [
{
'test6/test6': []
}
],
'test7/test7': [],
'test7/test7': []
}
],
}例如,通过给出键'test/test‘并获得一个值列表来调用函数:
my_recursive_func('test/test')
test1/test1
test3/test3
test2/test2
test4/test4发布于 2022-04-13 12:33:44
你基本上有两种情况:
当您的字典在另一个字典中时
当您的字典位于字典数组中时
对于字典中的每个键,将该键放入键数组中,并使用嵌套字典回忆函数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']这个解决方案应该适用于任何给定的结构。
发布于 2022-04-13 12:31:10
此解决方案仅适用于特定的数据结构。
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 resultmy_recursive_func(DICTS['test/test'])
> ['test1/test1', 'test3/test3', 'test2/test2', 'test4/test4']https://stackoverflow.com/questions/71857200
复制相似问题