python - 测试字典键是否存在,不为空且不为空

标签 python python-3.x dictionary

我有可用的代码,但我想知道是否有更 pythonic 的方法来执行此操作。我有一本字典,我想看看是否:

  • 存在一个键
  • 该值不是 None(在本例中来自 SQL 的 NULL)
  • 该值不只是引用(空白?)
  • 该值不仅仅由空格组成

所以在我的代码中,“a”、“b”和“c”键会成功,这是正确的。

import re

mydict = {
"a":"alpha",
"b":0,
"c":False,
"d":None,
"e":"",
"g":"   ",
}

#a,b,c should succeed
for k in mydict.keys():
    if k in mydict and mydict[k] is not None and not re.search("^\s*$", str(mydict[k])):
        print(k)
    else:
        print("I am incomplete and sad")

我上面的内容有效,但这似乎是一组非常长的条件。也许这只是正确的解决方案,但我想知道是否有更 pythonic 的“存在​​并且有东西”或更好的方法来做到这一点?

更新 感谢大家的精彩回答和深思熟虑的评论。有了一些要点和技巧,我对问题进行了一些更新,因为有些条件我没有,但也应该成功。我还将示例更改为循环(这样更容易测试吧?)。

最佳答案

尝试获取值并将其存储在变量中,然后使用对象“truthyness”进一步处理该值

v = mydict.get("a")
if v and v.strip():
  • 如果 "a" 不在字典中,get 返回 None 并且第一个条件失败
  • 如果 "a" 在字典中但产生 None 或空字符串,则测试失败,如果 "a" 产生空字符串, strip() 返回虚假字符串,它也失败了。

让我们测试一下:

for k in "abcde":
    v = mydict.get(k)
    if v and v.strip():
        print(k,"I am here and have stuff")
    else:
        print(k,"I am incomplete and sad")

结果:

a I am here and have stuff
b I am incomplete and sad    # key isn't in dict
c I am incomplete and sad    # c is None
d I am incomplete and sad    # d is empty string
e I am incomplete and sad    # e is only blanks

如果您的值可以包含 False0 或其他“虚假”非字符串,您将必须测试字符串,在这种情况下替换:

if v and v.strip():

通过

if v is not None and (not isinstance(v,str) or v.strip()):

如果不是 None 并且不是字符串(所有内容都匹配)或者如果是字符串,则该字符串不为空,则条件匹配。

关于python - 测试字典键是否存在,不为空且不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50156550/

相关文章:

python - 在yarn-cluster模式下运行python Spark作业

python - 支持一个python包的两个版本,无需客户端更改代码

javascript - Python Websockets 无法通过互联网连接

python - 在 Python 中向字典添加元素

python - 代码运行良好,但似乎不是很 Pythonic - 我如何改进这个字典的创建以及从该字典创建组合?

Windows XML 输出的 Python ETREE 解析

python - 索引错误 : list out of range in a while loop

python - 从深层嵌套列表/元组中提取元素的递归函数

python - 将两个具有相同键但不同字典作为值的嵌套字典组合在一起

python - 使用 Django 在一页上登录和注册表格