我正在尝试在嵌套字典中查找键:
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):{}}
我已经检查了该线程(Finding a key recursively in a dictionary),但似乎正在做完全相同的事情...
当循环中没有条件返回时,即使结果为None,它也只会返回第一个结果。我添加了这样的支票:
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): {}}