I am trying to remove all values 'x'
from a large dictionary and NOT delete any keys, but when I run the code there are still 'x'
values remaining.
Here is an excerpt of my dictionary:
myDict = {0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2', 'x', 'x'], 2: ['id1', 'x', 'x', 'x']}
My code thus far:
for k, v in myDict.iteritems():
if v == 'x':
myDict.remove('x')
print myDict
What I am aiming for:
myDict = {0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2'], 2: ['id1']}
How should I remove the 'x'
values in the lists, please?
Remove Multiple elements from list by index range using del. Suppose we want to remove multiple elements from a list by index range, then we can use del keyword i.e. It will delete the elements in list from index1 to index2 – 1.
In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.
You could use a list comprehension within a dictionary comprehension as follows:
myDict = {k:[el for el in v if el != 'x'] for k, v in myDict.items()}
print(myDict)
Output
{0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2'], 2: ['id1']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With