![](/img/trans.png)
[英]How to check if dictionary is empty and dictionary is like {“”:“”} in python
[英]How to check an empty dictionary?
我有以下代碼。 如果詞典為空,我想寫一個條件。
belongingsList = []
for item, count in self.belongings.items():
if count >= 1:
belongingsList.append(item)
return belongingsList
如果字典為空,我想返回一個空列表
您可以使用len()
函數進行檢查,該函數應用於字典對象時,將檢查字典中鍵-值對的數量
belongingList = []
if len(belongings) == 0: # check if the dictionary is empty
return belongingList
else:
for item, count in self.belongings.items():
if count >= 1:
belongingsList.append(item)
return belongingList
另一種方式
belongingsList = []
if len(belongings) > 0: # check if the dictionary is not empty
for item, count in self.belongings.items():
if count >= 1:
belongingsList.append(item)
return belongingsList
您只需要在開始時簡單檢查一下它是否為空,然后返回一個空列表。 您還可以使用列表推導來簡化它,因此行數不多:
def yourFunction():
# Return an empty list if the dict is empty.
if not self.belongings:
return []
# Can use a list comprehension to simplify code.
return [item for item, count in self.belongings.items() if count >= 1]
老實說,您甚至不需要開始檢查,因為如果這是一個空dict
那么列表推導會返回一個空列表,如您所願:
def yourFunction():
return [item for item, count in self.belongings.items() if count >= 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.