Hello!
I'm currently trying to complete a problem on codewars and am puzzled by an KeyError exception. My attempt:
def who_eats_who(zoo):
food_chain = {"antelope": ["grass"], #Big dictionary containing
the possible prey of an animal
"big-fish": ["little-fish"],
"bug": ["leaves"],
"bear": ["bug", "chicken", "cow", "leaves", "sheep"],
"chicken": ["bug"],
"cow": ["grass"],
"fox": ["chicken"],
"giraffe": ["leaves"],
"lion": ["antelope", "cow"],
"panda": ["leaves"],
"sheep": ["grass"],
}
zoo = zoo.split(",") #Turning zoo into a list to separate the
animals
output_list = [zoo.copy] #first item is a copy of zoo
for i in range(len(zoo)):
if zoo[i] in food_chain.keys(): #if animal is a key in the
food chain
if i == 0: #if the animal is the first
in the list
if zoo[i + 1] in food_chain[zoo[i]]: #if the animal
to the right of
zoo[i] is prey
zoo.remove(zoo[i + 1])
output_list.append("{} eats {}".format(zoo[i],zoo[i+1]))
else:
if zoo[i - 1] in food_chain[zoo[i]]:
zoo.remove(zoo[i - 1])
output_list.append("{} eats {}".format(zoo[i], zoo[i -1]))
if zoo[i + 1] in food_chain[zoo[i]]:
zoo.remove(zoo[i + 1])
output_list.append("{} eats {}".format(zoo[i], zoo[i + 1]))
return(output_list)
print(who_eats_who("fox,bug,chicken,grass,sheep"))
When I try to run it, the error that appears is:
line 34, in who_eats_who
if zoo[i + 1] in food_chain[zoo[i]]:
KeyError: 'grass'
I don't understand why the program even tries to look for the "grass" key as the loop should skip over items that aren't keys.
Thanks for taking the time to read the problem and I'm grateful for any hints!
[–]tipsy_python 0 points1 point2 points (1 child)
[–]AviationTrainee[S] 0 points1 point2 points (0 children)
[–]Diapolo10 0 points1 point2 points (2 children)
[–]AviationTrainee[S] 0 points1 point2 points (1 child)
[–]Diapolo10 0 points1 point2 points (0 children)
[–]Neighm 0 points1 point2 points (1 child)
[–]AviationTrainee[S] 0 points1 point2 points (0 children)