Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要帮助从字典中删除空列表吗_Python - Fatal编程技术网

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。