如何检查“已设置”和“为空”?

2024-05-15 09:04:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从PHP转换到Python。在PHP中,isset()和empty()可以很容易地帮助您确定是设置了数组键(Python中的dictionary键)还是为空(false)。你知道吗

在Python3中,有没有一种简单的方法可以查看字典键是设置的还是空的?我注意到一些解决方案,这些解决方案指向各种尝试/例外捕获。你知道吗

PHP isset()函数

https://www.php.net/manual/en/function.isset.php

Determine if a variable is considered set, this means if a variable is declared and is different than NULL.

PHP empty()函数

https://www.php.net/manual/en/function.empty.php

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE.


Tags: 函数httpsnetifiswww解决方案manual
1条回答
网友
1楼 · 发布于 2024-05-15 09:04:52

您可以使用in测试字典中是否存在键:

>>> d = {'a': 'b', 'c': 'd'}
>>> 'a' in d
True
>>> 'x' in d
False

如果get中不存在键,还可以尝试查找值并获取默认值(默认情况下None):

>>> d.get('a')
'b'
>>> d.get('x')
>>> d.get('x') is None
True
>>> d.get('x', 'y')      # 'y' is the default value here
'y'

相关问题 更多 >