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.
dict[key]
exists and points to a non-empty string. TextString
replaced with the value assigned to dict[key]
.
dict[key]
exists and points to a empty string. TextString
replaced with "N/A"
.
dict[key]
doesn't exist. TextString
replaced with "N/A"
.
question from:
https://stackoverflow.com/questions/39903242/is-there-a-more-pythonic-way-to-combine-an-else-statement-and-an-except 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…