我有一本字典没有按照我的预期运行,它有什么问题?



示例字典

{
"01_timelines": {
"00_data-managment": {},
"01_rush-and-spot": {}
},
"02_source": {
"00_from_external": {
"01_fonts": {},
"02_logos": {},
"03_graphics": {},
"04_video": {},
"05_3d": {}
},
"01_imported_projects": {}

}

我看过:如何完全遍历一个未知深度的复杂字典?

和其他一些,但如果我在我的字典上运行函数,它将返回空??我不知道为什么。

我正在尝试创建一个自定义函数:

def print_dict(myfolders,depth,breadcrumb,olddepth):

depth += 1
for key,value in myfolders.items():

if isinstance(value, dict):
if depth == 0:
olddepth = depth
breadcrumb = []
# print(key)
breadcrumb.append(key)
elif depth != olddepth:
olddepth = depth
# tmp = breadcrumb
# tmp.pop()
# tmp.append(key)
breadcrumb.append(key)
print(breadcrumb,key)
else:
print(breadcrumb,key)

print_dict(value,depth,breadcrumb,olddepth)

但它并没有完全工作:输出需要是一个列表:

['01_timelines', '00_data-managment']
['01_timelines', '01_rush-and-spot']
['02_source', '00_from_external']
['02_source', '00_from_external','01_fonts']
['02_source', '00_from_external','02_logos']

劳动部

您可以将print_dict函数替换为以下函数并减少传递参数

myfolders = {
"01_timelines": {
"00_data-managment": {},
"01_rush-and-spot": {}
},
"02_source": {
"00_from_external": {
"01_fonts": {},
"02_logos": {},
"03_graphics": {},
"04_video": {},
"05_3d": {}
},
"01_imported_projects": {}
}
}
def print_dict(myfolders, breadcrumb=[]):
for key, value in myfolders.items():
breadcrumb_now = breadcrumb + [key]
print(breadcrumb_now)
if isinstance(value, dict):
if value: # if value dictionary is not empty then go deep
print_dict(myfolders[key], breadcrumb_now)
print_dict(myfolders)

这将导致以下输出

['01_timelines']
['01_timelines', '00_data-managment']
['01_timelines', '01_rush-and-spot']
['02_source']
['02_source', '00_from_external']
['02_source', '00_from_external', '01_fonts']
['02_source', '00_from_external', '02_logos']
['02_source', '00_from_external', '03_graphics']
['02_source', '00_from_external', '04_video']
['02_source', '00_from_external', '05_3d']
['02_source', '01_imported_projects']

尝试:

dct = {
"01_timelines": {"00_data-managment": {}, "01_rush-and-spot": {}},
"02_source": {
"00_from_external": {
"01_fonts": {},
"02_logos": {},
"03_graphics": {},
"04_vid1eo": {},
"05_3d": {},
},
"01_imported_projects": {},
},
}

def get_lists(d, breadcrumb=None):
if breadcrumb is None:
breadcrumb = []
if isinstance(d, dict):
for k in d:
new_breadcrumb = [*breadcrumb, k]
yield new_breadcrumb
yield from get_lists(d[k], new_breadcrumb)

print(list(get_lists(dct)))

打印:

[
["01_timelines"],
["01_timelines", "00_data-managment"],
["01_timelines", "01_rush-and-spot"],
["02_source"],
["02_source", "00_from_external"],
["02_source", "00_from_external", "01_fonts"],
["02_source", "00_from_external", "02_logos"],
["02_source", "00_from_external", "03_graphics"],
["02_source", "00_from_external", "04_vid1eo"],
["02_source", "00_from_external", "05_3d"],
["02_source", "01_imported_projects"],
]

最新更新