提问人:Abbas Kanj 提问时间:11/12/2023 最后编辑:ndcltAbbas Kanj 更新时间:11/13/2023 访问量:63
如何在字典中打印重复键的值?
How can I print the values of duplicate keys in a dictionary?
问:
它只打印嵌套标题中的最后一个键值对。
这是我正在使用的代码:
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 标题。
答:
-1赞
new92
11/13/2023
#1
尝试使用此解决方案
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”字典中的项目放在列表中。我想不出任何其他方法可以在不遇到错误的情况下检索该信息。
评论
d = {'a': 1, 'b': 2, 'a': 3}
dict_items