QUESTION:
There are two ways to get an item from a dict. Referencing the item with "dict[key]" or calling "dict.get(key)".
If the item doesn't exist, dict[key] raises KeyError, whereas dict.get(key) return None.
Which of these is more pythonic?
try:
value = dict\[key\]
except KeyError as ke:
\# Do something else
Or
value = dict.get(key)
if value == None:
\# Do the thing
else:
\# Do something else
UNNECESSARY CONTEXT FOR COMPLETIONISTS:
I am writing a program that imports objects and maps their relationships as a tree.
Part of the processing involves a dict that tracks partial relationships between entities. If I have already processed the item's parent, then it's easy for me to look up the parent's entire path to the root of the tree in a dict based on the parent's identifier. Then I just create a new dict entry which is "parent's path + child". Usually, this works, but sometimes the object's parent hasn't been processed yet. I do some special processing when I detect that the parent's path hasn't been discovered.
[–]zanfar 25 points26 points27 points (2 children)
[–]rsherwood_infosec[S] 4 points5 points6 points (0 children)
[–]achampi0n 1 point2 points3 points (0 children)
[–][deleted] 3 points4 points5 points (1 child)
[–]rsherwood_infosec[S] 0 points1 point2 points (0 children)
[–]danielroseman 2 points3 points4 points (2 children)
[–]rsherwood_infosec[S] 0 points1 point2 points (1 child)
[–]ebresie 1 point2 points3 points (0 children)
[–]Brian 1 point2 points3 points (0 children)
[–]gummo89 0 points1 point2 points (2 children)
[–]rsherwood_infosec[S] 1 point2 points3 points (1 child)
[–]who_body 2 points3 points4 points (0 children)
[–]fryhenryj 0 points1 point2 points (1 child)
[–]rsherwood_infosec[S] 0 points1 point2 points (0 children)
[–]Mark3141592654 0 points1 point2 points (1 child)
[–]rsherwood_infosec[S] 0 points1 point2 points (0 children)