[英]Need help to remove empty lists from dictionaries
我有這本字典:
a_dict = {1: "hello", 2: [], 3: [], 4: "hey", 5:"phone"}
我想從這本字典中刪除所有空列表。
Output: a_dict = {1:"hello",4:"hey",5:"phone"}
我試過這個:
for item in a_dict:
if a_dict[item] == []:
del item
但是,這只是歸還原始字典。 它對它沒有任何作用。
在迭代它時,您不應該刪除 dict 的鍵。 您可以將密鑰保存在其他變量中並使用它來刪除密鑰。 這是一個與您當前的代碼非常相似的解決方案。
deleteKeys = []
for item in a_dict:
if a_dict[item] == []:
deleteKeys.append(item)
for i in deleteKeys:
del a_dict[i]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.