需要帮助从字典中删除空列表

时间:2021-05-20 19:00:06

标签: 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[item] == []:
            del item

然而,这只是返回原始字典。它对它没有任何作用。

1 个答案:

答案 0 :(得分:1)

您不应该在迭代时删除字典的键。您可以将您的密钥保存在其他一些变量中并使用它来删除密钥。这是一个与您当前的代码非常相似的解决方案。

def add_hours(self, chores, time):
    if chores in self.chores:
        self.chores[chores] += time
    else:
        self.chores[chores] = time