python - 如何从字典中删除列表值?

标签 python dictionary

给定一个以列表作为值的字典。

myDict = {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]}

如果值列表为空,如何从字典中删除项目?

我尝试遍历字典并删除项目,但在迭代期间不允许更改字典大小。

for item in myDict:
    if myDict[item] == []:
        print item
        del myDict[item]

最佳答案

使用字典理解:

>>> myDict = {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]}
>>> myDict = {k: v for k, v in myDict.items() if v}
>>> myDict
{0: [0, 1, 2], 2: [20, 25, 26, 28, 31, 34], 4: [0, 1, 2, 3, 4, 7, 10], 6: [10, 20, 24]}

迭代时不允许添加、删除字典条目。制作 key 的副本以克服它。例如,在下面,我使用 tuple(myDict) 来获取键的副本。

>>> myDict =  {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]}
>>> for item in tuple(myDict):
...     if myDict[item] == []:
...         del myDict[item]
...
>>> myDict
{0: [0, 1, 2], 2: [20, 25, 26, 28, 31, 34], 4: [0, 1, 2, 3, 4, 7, 10], 6: [10, 20, 24]}

关于python - 如何从字典中删除列表值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20249397/

相关文章:

python - 发送带有指定值的 request.get 下拉表

python - 使用 python 获取我的 IP

string - '(NSObject, AnyObject )' is not convertible to ' 字符串'

python - 在python中求解联立方程

python - Python的序列协议(protocol)是什么?

python - 替换 Python 列表字典中的项目

python - 如何找到计数器的第二个最大值 - Python

ios - lexicontext ios sdk是否在utf8中提供自动完成

swift - 如何使用字典中的所有数据填充 tableView?

python - Windows下获取系统信息(CPU速度-总RAM-显卡型号等)