它仅打印嵌套标题中的最后一个键值对。
这是我正在使用的代码:
def displayAllTabs(dict_items):
for dict in dict_items:
title = dict.get("Title")
print(title)
if "NestedTabs" in dict.keys():
nestedTitle = dict["NestedTabs"]["Title"]
print(f'\t{nestedTitle}')
这是我的清单:
[
{
"index": 1,
"Title": "SE Factory",
"Url": "https://www.sefactory.io",
"NestedTabs": {"Title": "UI", "Url": "https://www.sefactory.io/uix"},
},
{"index": 2, "Title": "Google", "Url": "https://www.google.com"},
{
"index": 3,
"Title": "W3schools",
"Url": "https://www.w3schools.com",
"NestedTabs": {
"Title": "Html",
"Url": "https://www.w3schools.com/html/default.asp",
"Title": "Css",
"Url": "https://www.w3schools.com/css/default.asp",
"Title": "JavaScript",
"Url": "https://www.w3schools.com/js/default.asp",
},
},
]
例如:在 w3schools 嵌套选项卡中,它仅打印 Javascript 标题。
尝试使用此解决方案
def displayAllTabs(dict_items):
for item in dict_items:
title = item.get("Title")
print(title)
if "NestedTabs" in item:
nested_tabs = item['NestedTabs']
if "Title" in nested_tabs and "Url" in nested_tabs:
nested_title = nested_tabs["Title"]
nested_url = nested_tabs["Url"]
print(f'\tNested Tab: {nested_title} ({nested_url})')
elif isinstance(nested_tabs, list):
for nested_tab in nested_tabs:
nested_title = nested_tab.get("Title")
nested_url = nested_tab.get("Url")
print(f'\tNested Tab: {nested_title} ({nested_url})')
dict_items = [
{
"index": 1,
"Title": "SE Factory",
"Url": "https://www.sefactory.io",
"NestedTabs": [{"Title": "UI", "Url": "https://www.sefactory.io/uix"}],
},
{"index": 2, "Title": "Google", "Url": "https://www.google.com"},
{
"index": 3,
"Title": "W3schools",
"Url": "https://www.w3schools.com",
"NestedTabs": [
{"Title": "Html", "Url": "https://www.w3schools.com/html/default.asp"},
{"Title": "Css", "Url": "https://www.w3schools.com/css/default.asp"},
{"Title": "JavaScript", "Url": "https://www.w3schools.com/js/default.asp"},
],
},
]
displayAllTabs(dict_items=dict_items)
您需要将“NestedTabs”字典的项目放入列表中。我想不出任何其他方法可以在不遇到错误的情况下检索该信息。