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"
.
This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.
You can use multiple else if but each of them must have opening and closing curly braces {} .
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.
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"
Use get()
function for dictionaries. It will return None
if the key doesn't exist or if you specify a second value, it will set that as the default. Then your syntax will look like:
nObject.TextString = self.var.jobDetails.get('Overall Weight', 'N/A')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With