Reputation: 6312
Given a dictionary with lists as values.
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]}
How can I remove items from the dictionary if the value list is empty?
I tried to iterate over the dictionary and remove items, but the dictionary size is not allowed to change during iteration.
for item in myDict:
if myDict[item] == []:
print item
del myDict[item]
Upvotes: 3
Views: 177
Reputation: 223
for k in myDict.keys():
if myDict[k] == []:
del myDict[k]
This will remove any key for which the value is and empty array.
Upvotes: 0
Reputation: 369424
Using dict comprehension:
>>> 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]}
Adding, deleting dictionary entries are not allowed while iterating it. Make a copy of keys to overcome it. For example, in the following, I used tuple(myDict)
to get copy of the keys.
>>> 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]}
Upvotes: 5