How to remove a list value from a dictionary?

dictionary, python

Solution

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]}

Problem

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] ```

Original source