In a class I have a nested dict
tree = {"left":tree_left,"right":tree_right,"class":class,"split":split}
where tree_left,tree_right
also are dictionaries on the same form.
If I write
tree = self.tree
while tree["split"]:
do stuff
it throws the KeyError: "split"
but writing
tree = self.tree
while tree.get("split"):
do stuff
it works. I have furthermore tried
tree = self.tree
print(tree["split"])
while tree["split"]:
do stuff
which prints the correct value and then throws the error.
Any reason why ?
When tree doesn't have split key, tree["split"]
will throw KeyError
exception while tree.get("split")
will return None
and the code will exit the while loop without any exception (the loop condition will be logically False
).
Another way to check if split exists in your tree variable would be:
while "split" in tree:
# do stuff