本文翻译自:Python: Checking if a 'Dictionary' is empty doesn't seem to work
I am trying to check if a dictionary is empty but it doesn't behave properly. 我正在尝试检查字典是否为空但它的行为不正常。 It just skips it and displays ONLINE without anything except of display the message. 除了显示消息之外,它只是跳过它并显示ONLINE而没有任何内容。 Any ideas why ? 有什么想法吗?
def isEmpty(self, dictionary):
for element in dictionary:
if element:
return True
return False
def onMessage(self, socket, message):
if self.isEmpty(self.users) == False:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
参考:https://stackoom.com/question/1ZFVf/Python-检查-Dictionary-是否为空似乎不起作用
Empty dictionaries evaluate to False
in Python: Python中的空字典评估为False
:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
Thus, your isEmpty
function is unnecessary. 因此,您的isEmpty
函数是不必要的。 All you need to do is: 你需要做的就是:
def onMessage(self, socket, message):
if not self.users:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
Here are three ways you can check if dict is empty. 以下三种方法可以检查dict是否为空。 I prefer using the first way only though. 我更喜欢使用第一种方式。 The other two ways are way too wordy. 另外两种方式太过于罗嗦。
test_dict = {}
if not test_dict:
print "Dict is Empty"
if not bool(test_dict):
print "Dict is Empty"
if len(test_dict) == 0:
print "Dict is Empty"
use 'any' 使用'任何'
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
Why not use equality test? 为什么不使用平等测试?
def is_empty(my_dict):
"""
Print true if given dictionary is empty
"""
if my_dict == {}:
print("Dict is empty !")
dict = {}
print(len(dict.keys()))
if length is zero means that dict is empty 如果length为零则表示dict为空