[英]How to check if a dictionary is empty?
我正在嘗試檢查字典是否為空,但它的行為不正常。 它只是跳過它並顯示在線,除了顯示消息之外沒有任何內容。 任何想法為什么?
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()))
空字典在 Python 中評估為False
:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
因此,您的isEmpty
函數是不必要的。 您需要做的就是:
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()))
您可以通過以下三種方法檢查 dict 是否為空。 不過,我更喜歡使用第一種方式。 其他兩種方式太羅嗦了。
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"
dict = {}
print(len(dict.keys()))
如果長度為零意味着 dict 為空
檢查空字典的簡單方法如下:
a= {}
1. if a == {}:
print ('empty dict')
2. if not a:
print ('empty dict')
雖然方法 1 更嚴格,因為當 a = None 時,方法 1 會提供正確的結果,但方法 2 會給出不正確的結果。
字典可以自動轉換為布爾值,對於空字典評估為False
,對於非空字典評估為True
。
if myDictionary: non_empty_clause()
else: empty_clause()
如果這看起來太慣用了,您還可以測試len(myDictionary)
為零,或set(myDictionary.keys())
為空集,或者簡單地測試與{}
是否相等。
isEmpty 函數不僅是不必要的,而且您的實現還有多個我可以發現的問題。
return False
語句縮進一級太深。 它應該在 for 循環之外並與for
語句處於同一級別。 因此,如果鍵存在,您的代碼將只處理一個任意選擇的鍵。 如果鍵不存在,該函數將返回None
,它將被轉換為布爾值 False。 哎喲! 所有空字典都將被歸類為假否定。return False
語句的縮進,並將其置於for
循環之外。 然后你得到的是所有鍵的布爾值OR ,如果字典為空,則為False
。 你仍然會有誤報和漏報。 對照以下字典進行更正和測試以獲取證據。 myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
您也可以使用 get()。 最初我相信它只檢查密鑰是否存在。
>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
我喜歡 get 的是它不會觸發異常,因此可以輕松遍歷大型結構。
Python 3:
def is_empty(dict):
if not bool(dict):
return True
return False
test_dict = {}
if is_empty(test_dict):
print("1")
test_dict = {"a":123}
if not is_empty(test_dict):
print("1")
單程:
len(given_dic_obj)
如果沒有元素則返回 0 否則返回字典的大小。
第二種方式:
bool(given_dic_object)
如果字典為空則返回 True 否則返回 false
我用:
if len(dict)>0:
# True
else:
# False
test_dict = {}
if not test_dict.keys():
print "Dict is Empty"
為什么不使用平等測試?
def is_empty(my_dict):
"""
Print true if given dictionary is empty
"""
if my_dict == {}:
print("Dict is empty !")
使用“任何”
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.