RBuntu RBuntu - 2 months ago 8
Python Question

Is there a more Pythonic way to combine an Else: statement and an Except:?

I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg.

"overall_weight"
in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cases, the
"overall_weight"
keywords should be replaced with
"N/A"
. I was wondering if there was a more pythonic way to combine the
KeyError
exception and the
else
to both go to
nObject.TextString = "N/A"
so its not typed twice.

if nObject.TextString == "overall_weight":
try:
if self.var.jobDetails["Overall Weight"]:
nObject.TextString = self.var.jobDetails["Overall Weight"]
else:
nObject.TextString = "N/A"
except KeyError:
nObject.TextString = "N/A"


Edit: For clarification for future visitors, there are only 3 cases I need to take care of and the correct answer takes care of all 3 cases without any extra padding.


  1. dict[key]
    exists and points to a non-empty string.
    TextString
    replaced with the value assigned to
    dict[key]
    .

  2. dict[key]
    exists and points to a empty string.
    TextString
    replaced with
    "N/A"
    .

  3. dict[key]
    doesn't exist.
    TextString
    replaced with
    "N/A"
    .


pzp pzp
Answer

Use dict.get() which will return the value associated with the given key if it exists otherwise None. (Note that '' and None are both falsey values.) If s is true then assign it to nObject.TextString otherwise give it a value of "N/A".

if nObject.TextString == "overall_weight":
    nObject.TextString = self.var.jobDetails.get("Overall Weight") or "N/A"