检查一个键是否存在并且它的值不是 Python 字典中的空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14323045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:04:50  来源:igfitidea点击:

Checking if a key exists and its value is not an empty string in a Python dictionary

pythondictionarystring

提问by Jonathan Evans

Is there a clear best practice for assigning a variable from a key/value pair in a Python dictionary:

从 Python 字典中的键/值对中分配变量是否有明确的最佳实践:

  • If the key is present
  • If the key's value is not an empty string
  • 如果密钥存在
  • 如果键的值不是空字符串

And otherwise assigning a default value to the variable.

否则为变量分配一个默认值。

I would like to use dict.get:

我想使用dict.get

my_value = dict.get(key, my_default)

But this assigns an empty string to my_valueif the key is present and the value is an empty string. Is it better to use the following:

但是my_value如果键存在并且值是空字符串,则这会分配一个空字符串。使用以下内容是否更好:

if key in dict and dict[key]:
    my_value = dict[key]
else:
    my_value = my_default

This would make use of the truthfulness of an empty string to ensure only non-empty strings were assigned to my_value.

这将利用空字符串的真实性来确保仅将非空字符串分配给my_value

Is there a better way to perform this check?

有没有更好的方法来执行此检查?

采纳答案by mgilson

Maybe you mean something like:

也许你的意思是这样的:

a.get('foo',my_default) or my_default

which I think should be equivalent to the if-elseconditional you have

我认为这应该等同于if-else您拥有的条件

e.g.

例如

>>> a = {'foo':''}
>>> a.get('foo','bar') or 'bar'
'bar'
>>> a['foo'] = 'baz'
>>> a.get('foo','bar') or 'bar'
'baz'
>>> a.get('qux','bar') or 'bar'
'bar'

The advantages to this over the other version are pretty clear. This is nice because you only need to perform the lookup once and because orshort circuits (As soon as it hits a Truelike value, it returns it. If no True-like value is found, orreturns the second one).

与其他版本相比,它的优势非常明显。这很好,因为您只需要执行一次查找并且因为or短路(一旦遇到True类似值,它就会返回它。如果没有找到类似 True 的值,则or返回第二个)。

If your default is a function, it couldbe called twice if you write it as: d.get('foo',func()) or func(). In this case, you're better off with a temporary variable to hold the return value of func.

如果您的默认值是一个函数,则可以将其编写为: 两次调用它 d.get('foo',func()) or func()。在这种情况下,最好使用一个临时变量来保存func.

回答by Mark Ransom

The simplest way to do what you want:

做你想做的最简单的方法:

my_value = dict.get(key) or my_default

The orwill deliver the first value if it evaluates non-false, otherwise the second one. Unlike other languages Python doesn't force the result to be boolean, quite a useful property sometimes.

or如果结果不假,否则,第二个将交付第一个值。与其他语言不同,Python 不会强制结果为布尔值,有时这是一个非常有用的属性。