简体   繁体   English

检查键是否存在且其值不是 Python 字典中的空字符串

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

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_value if the key is present and the value is an empty string.但是,如果键存在并且值是空字符串,则会将空字符串分配给my_value Is it better to use the following:使用以下内容是否更好:

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?有没有更好的方法来执行此检查?

Maybe you mean something like: 也许你的意思是:

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

which I think should be equivalent to the if-else conditional you have 我认为应该等同于你拥有的if-else条件

eg 例如

>>> 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 or short circuits (As soon as it hits a True like value, it returns it. If no True-like value is found, or returns the second one). 这很好,因为你只需要执行一次查找和因为or短路(一旦它达到类似True值,它就会返回它。如果没有找到类似True的值, or返回第二个值)。

If your default is a function, it could be called twice if you write it as: d.get('foo',func()) or func() . 如果您的默认值是一个函数,如果您将其写为: d.get('foo',func()) or func() ,则可以调用它两次。 In this case, you're better off with a temporary variable to hold the return value of func . 在这种情况下,最好使用临时变量来保存func的返回值。

The simplest way to do what you want: 做你想做的最简单的方法:

my_value = dict.get(key) or my_default

The or will deliver the first value if it evaluates non-false, otherwise the second one. or如果它的计算结果非假将提供第一值,否则第二个。 Unlike other languages Python doesn't force the result to be boolean, quite a useful property sometimes. 与其他语言不同,Python不强制结果为布尔值,有时是非常有用的属性。

this worked for me这对我有用

    try:
        post_profile = record['ownerUsername'] 

    except KeyError:
        post_profile = "nouserwasfound"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM