是否有更多Pythonic方式结合Else:语句和Except:?

时间:2022-03-07 22:20:15

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.

我有一段代码在AutoCAD中搜索包含某些关键字的文本框(例如,在这种情况下为“overall_weight”),并将其替换为字典中的值。但是,有时字典键被分配给空字符串,有时,键不会完全存在。在这些情况下,“overall_weight”关键字应替换为“N / A”。我想知道是否有一种更加pythonic方式将KeyError异常和else结合起来转到nObject.TextString =“N / A”所以它没有输入两次。

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.

编辑:为了澄清未来的访问者,我只需要处理3个案例,正确的答案可以处理所有3个案例而不需要任何额外的填充。

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

    dict [key]存在并指向非空字符串。 TextString替换为分配给dict [key]的值。

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

    dict [key]存在并指向空字符串。 TextString替换为“N / A”。

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

    dict [key]不存在。 TextString替换为“N / A”。

6 个解决方案

#1


66  

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

使用dict.get()将返回与给定键关联的值(如果存在则返回None)。 (注意''和None都是假值。)如果s为真,则将其分配给nObject.TextString,否则给它一个值“N / A”。

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

#2


17  

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:

使用字典的get()函数。如果密钥不存在,或者如果指定第二个值,它将返回None,它会将其设置为默认值。然后你的语法将如下所示:

nObject.TextString = self.var.jobDetails.get('Overall Weight', 'N/A')

#3


9  

Use .get() with a default argument of "N/A" which will be used if the key does not exist:

使用.get(),默认参数为“N / A”,如果密钥不存在,将使用该参数:

nObject.TextString = self.var.jobDetails.get("Overall Weight", "N/A")

Update

If empty strings need to be handled, simply modify as follows:

如果需要处理空字符串,只需修改如下:

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

This will set nObject.TextString to "N/A" if a KeyError is raised, or if the value is retrieved is empty: '', [], etc.

如果引发KeyError,或者如果检索到的值为空,则将nObject.TextString设置为“N / A”:'',[]等。

#4


3  

I think this is a good case for setting the default value in advance

我认为这是提前设置默认值的好例子

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

RADICAL RETHINK

RADICAL RETHINK

Ditch that first answer (just keeping it because it got an upvote). If you really want to go pythonic, (and you always want to set a value on TextString) replace the whole thing with

沟通第一个回答(只是保留它,因为它有一个upvote)。如果你真的想去pythonic,(你总是想在TextString上设置一个值)替换整个东西

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

Python and and or operations return their last calculated value, not True/False and you can use that to walk through the combinations.

Python和和或操作返回它们的最后计算值,而不是True / False,您可以使用它来遍历组合。

#5


2  

The Zen of Python says "Explicit is better than implicit." I have found this to be very true in my own experience. When I write a piece of code I think to my self, "Will I understand what this means a year from now?" If the answer is "no" then it needs to be re-written or documented. The accepted answer relies on remembering the implementation of dict.get to know how it will handle the corner cases. Since the OP has 3 clear criteria, I would instead document them clearly in an if statement.

Python的禅宗说“明确比隐含更好”。我发现这在我自己的经历中是非常真实的。当我写一段代码时,我想我自己,“我能理解一年后这意味着什么吗?”如果答案是“否”,则需要重新编写或记录。接受的答案依赖于记住dict.get的实现,以了解它将如何处理极端情况。由于OP有3个明确的标准,我会在if语句中清楚地记录它们。

if nObject.TextString == "overall_weight" and \
    "Overall Weight" in self.var.jobDetails and \
    self.var.jobDetails["Overall Weight"] != "":
    nObject.TextString = self.var.jobDetails["Overall Weight"]
else:
    nObject.TextString = "N/A"

It's certainly more verbose... but that's a good thing. There is no question when reading this what the behavior will be.

它当然更加冗长......但这是一件好事。毫无疑问,阅读此行为将是什么。

#6


-2  

How about with:

怎么样:

key = 'Overall Weight'

with n_object.text_string = self.var.job_details[key]:
    if self.var.job_details[key] is None \
    or if self.var.job_details[key] is '' \
    or if KeyError:
        n_object.text_string = 'N/A'

#1


66  

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

使用dict.get()将返回与给定键关联的值(如果存在则返回None)。 (注意''和None都是假值。)如果s为真,则将其分配给nObject.TextString,否则给它一个值“N / A”。

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

#2


17  

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:

使用字典的get()函数。如果密钥不存在,或者如果指定第二个值,它将返回None,它会将其设置为默认值。然后你的语法将如下所示:

nObject.TextString = self.var.jobDetails.get('Overall Weight', 'N/A')

#3


9  

Use .get() with a default argument of "N/A" which will be used if the key does not exist:

使用.get(),默认参数为“N / A”,如果密钥不存在,将使用该参数:

nObject.TextString = self.var.jobDetails.get("Overall Weight", "N/A")

Update

If empty strings need to be handled, simply modify as follows:

如果需要处理空字符串,只需修改如下:

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

This will set nObject.TextString to "N/A" if a KeyError is raised, or if the value is retrieved is empty: '', [], etc.

如果引发KeyError,或者如果检索到的值为空,则将nObject.TextString设置为“N / A”:'',[]等。

#4


3  

I think this is a good case for setting the default value in advance

我认为这是提前设置默认值的好例子

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

RADICAL RETHINK

RADICAL RETHINK

Ditch that first answer (just keeping it because it got an upvote). If you really want to go pythonic, (and you always want to set a value on TextString) replace the whole thing with

沟通第一个回答(只是保留它,因为它有一个upvote)。如果你真的想去pythonic,(你总是想在TextString上设置一个值)替换整个东西

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

Python and and or operations return their last calculated value, not True/False and you can use that to walk through the combinations.

Python和和或操作返回它们的最后计算值,而不是True / False,您可以使用它来遍历组合。

#5


2  

The Zen of Python says "Explicit is better than implicit." I have found this to be very true in my own experience. When I write a piece of code I think to my self, "Will I understand what this means a year from now?" If the answer is "no" then it needs to be re-written or documented. The accepted answer relies on remembering the implementation of dict.get to know how it will handle the corner cases. Since the OP has 3 clear criteria, I would instead document them clearly in an if statement.

Python的禅宗说“明确比隐含更好”。我发现这在我自己的经历中是非常真实的。当我写一段代码时,我想我自己,“我能理解一年后这意味着什么吗?”如果答案是“否”,则需要重新编写或记录。接受的答案依赖于记住dict.get的实现,以了解它将如何处理极端情况。由于OP有3个明确的标准,我会在if语句中清楚地记录它们。

if nObject.TextString == "overall_weight" and \
    "Overall Weight" in self.var.jobDetails and \
    self.var.jobDetails["Overall Weight"] != "":
    nObject.TextString = self.var.jobDetails["Overall Weight"]
else:
    nObject.TextString = "N/A"

It's certainly more verbose... but that's a good thing. There is no question when reading this what the behavior will be.

它当然更加冗长......但这是一件好事。毫无疑问,阅读此行为将是什么。

#6


-2  

How about with:

怎么样:

key = 'Overall Weight'

with n_object.text_string = self.var.job_details[key]:
    if self.var.job_details[key] is None \
    or if self.var.job_details[key] is '' \
    or if KeyError:
        n_object.text_string = 'N/A'