Python - 檢查字典是否為空


在分析資料集時,我們可能會遇到必須處理空字典的情況。在本文中,我們將學習如何檢查字典是否為空。

使用 if

如果字典中有元素,if 條件將變為 true。否則,它將變為 false。所以,在下面的程式中,我們將僅使用 if 條件檢查字典的空情況。

示例

 動態演示

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
if dict1:
   print("dict1 is not empty")
else:
   print("dict1 is empty")
if dict2:
   print("dict2 is not empty")
else:
   print("dict2 is empty")

輸出

執行上面的程式碼將得到以下結果 −

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty

使用 bool()

如果字典不為空,則 bool 方法將變為 true。否則,它將變為 false。所以,我們在表示式中使用它來列印字典是否為空的結果。

示例

 動態演示

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
print("Is dict1 empty? :",bool(dict1))
print("Is dict2 empty? :",bool(dict2))

輸出

執行上面的程式碼將得到以下結果 −

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : True
Is dict2 empty? : False

更新於: 03-Mar-2020

6K+ 瀏覽

開啟你的 \職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.