给出一个列表作为值的字典。
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]
答案 0 :(得分:5)
使用dict理解:
>>> 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]}
在迭代时不允许添加,删除字典条目。制作钥匙的副本以克服它。例如,在下文中,我使用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]}
答案 1 :(得分:0)
for k in myDict.keys():
if myDict[k] == []:
del myDict[k]
这将删除值为的任何键和空数组。