Python 在嵌套字典中查找关键字
我试图在嵌套字典中找到一个键:Python 在嵌套字典中查找关键字,python,nested-loops,Python,Nested Loops,我试图在嵌套字典中找到一个键: mydict = { ('Geography', 1): {}, ('Languages', 2): { ('English', 3): { ('Grammar', 6): { ('new', 10):{}, ('old', 11): {} } }, ('Spanish', 4): {},
mydict = {
('Geography', 1): {},
('Languages', 2): {
('English', 3): {
('Grammar', 6): {
('new', 10):{},
('old', 11): {}
}
},
('Spanish', 4): {},
('French', 5): {
('Grammar', 7): {}
},
('Dutch', 8): {
('Grammar', 9): {
('new', 12):{}
}
}
}
}
因此,我在字典中循环查找键('Grammar',9)
,例如:
def _loop(topic, topics_dict):
if (topic[0], topic[1]) in topics_dict.keys():
return topics_dict[(topic[0], topic[1])]
else:
for k, v in topics_dict.items():
if v != {}:
return _loop(topic, v)
topic = ('Grammar', 9)
trim_mydict = _loop(topic, mydict)
print(trim_mydict)
但是,实际上,它返回None
而不是{('new',12):{}}
我已经检查了这个线程(),但我似乎在做完全相同的事情…当您在循环中返回而没有条件时,它只返回第一个结果,即使没有。我加了一张这样的支票:
mydict = {
('Geography', 1): {},
('Languages', 2): {
('English', 3): {
('Grammar', 6): {
('new', 10):{},
('old', 11): {}
}
},
('Spanish', 4): {},
('French', 5): {
('Grammar', 7): {}
},
('Dutch', 8): {
('Grammar', 9): {
('new', 10):{}
}
}
}
}
def _loop(topic, topics_dict):
if (topic[0], topic[1]) in topics_dict.keys():
return topics_dict[(topic[0], topic[1])]
else:
for k, v in topics_dict.items():
if v != {}:
if (result := _loop(topic, v)) is not None:
return result
topic = ('Grammar', 9)
trim_mydict = _loop(topic, mydict)
print(trim_mydict)
>>> {('new', 10): {}}
只是一个建议,您是否尝试了链接页面上的其他解决方案?在递归之前,您正在测试v是否不是字典。这将使代码立即停止,因为您确实有嵌套字典。编辑:对不起,我误读了:)你只是在检查它是否为空