简体   繁体   中英

Python dict keyerror in while statement (.get() works)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM