I have a while loop:
while parent != None:
pathList.append(parentMap[parent])
parent = parentMap[parent]
What I want to do with this list is simply add the parent value (already determined in other parts of the code) of a parent value to a list until I’ve reached the top of a tree and there are no more parents remaining. The while loop operates under the idea that once parentMap[parent] is provided with an invalid [parent] key, it will be assigned the value of “None” and the loop will terminate. This doesn’t happen. Instead, once I get to the topmost key, (5, 5), the program throws an error stating “invalid key.” Thoughts?
The problem, as others have also pointed out, is in the fact that a
dictdoesn’t returnNoneif a key isn’t found but instead raises aKeyErrorexception (as seen in the documentation).To overcome this you could use
defaultdictfromcollectionsand setNoneto be the default value for that dict. I recommend you read the classes documentation.In this case, instead of initializing your
dictasparentMap = dict(some_initializer)orparentMap = {}you could useparentMap = defaultdict(lambda: None, some_initializer)orparentMap = defaultdict(lambda: None, {})and missing keys will returnNonerather than raisingKeyErrorexceptions.In an unrelated issue,
Noneis a singleton, It’s better to check if anitem is not Nonerather than using!=. It generates clearer code, in my humble opinion.