[英]How to check dict of a list is empty?
這個想法是檢查 dict 中的列表中的以下 dict 是否為空。
例如,下面的字典
expected_false={"all_dict": [{"A": [1], "B": [], "C": [], "D": []}]}
應該返回空為假,因為鍵 'A' 的值為 1。
而以下內容應返回空為真
expected_empty={"all_dict": [{"A": [], "B": [], "C": [], "D": []}]}
我嘗試了以下代碼,但它給出的與我的想法不同。
all(not d for d in expected_true['all_dict'][0])
any(len(item) for item in expected_true['all_dict'][0].values())
這應該有效:
print(not any(len(expected_false['all_dict'][x]) > 0 for x in expected_false['all_dict']))
字典是一組鍵值對。 偽代碼:
-Get value of 'all_dict' key inside of dictionary that named {expected_false}
-That 'all_dict' key has a value which is a list that contains only one item (which is an another dictionary)
-To address list item : ['all_dict'][0] (we reached first list item, which is a dictionary)
-Use dict.values() method to get all values of keys innermost dictionary
-And each of these values are also list by itself
expected_false['all_dict'][0].values()
因此上面的代碼返回列表。 並檢查每個列表中是否有任何項目。 然后打印結果。
expected_false={"all_dict": [{"A": [1], "B": [], "C": [], "D": []}]}
for item in expected_false['all_dict'][0].values():
if len(item)!=0:
a=any(item)
print(a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.