Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - 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".

question from:https://stackoverflow.com/questions/39903242/is-there-a-more-pythonic-way-to-combine-an-else-statement-and-an-except

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...