Python 需要帮助从字典中删除空列表吗
我有这本字典:Python 需要帮助从字典中删除空列表吗,python,Python,我有这本字典: 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[
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]
dela_dict[item]
@Barmar“在迭代过程中dict大小发生了变化”
?a_dict={k:v代表k,v代表a_dict.items()如果v}
代表列表中的项(a_dict):
复制一份。@DeepSpace Oops,我假设你是OP。