I have some items in a nested dictionary and I need to match if any word in a sentence matches the values in the dictionary. If it does, it returns all the keys from the nested list.
What I have tried so far:
animals = {
'vertebrates': {
'warm_blooded': {
'mammals': ['bear', 'tiger', 'lion'],
'birds': ['eagle', 'ostrich', 'duck']
},
'cold_blooded': {
'reptiles': ['turtle', 'crocodile'],
'amphibians': ['frog', 'toad']
}
}
}
line = 'lions live in the savanna.'
for key1, value1 in animals.items():
for key2, value2 in value1.items():
for key3, value3 in value2.items():
if any(word in line for word in value3):
print ([key1, key2, key3])
>>> ['vertebrates', 'warm_blooded', 'mammals']
Currently it does what I need. What I want to know if there's a way to re-write this code in a more pythonic (elegant) way as this for loop might get longer if there's more levels in the dictionary to to tranverse through.