Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple values from [list] dictionary python

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?

like image 567
imasnake Avatar asked Mar 01 '16 12:03

imasnake


People also ask

How do you remove multiple values from a list in Python?

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.

How do I remove a list of numbers from a list in Python?

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.


1 Answers

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']}
like image 66
gtlambert Avatar answered Sep 27 '22 22:09

gtlambert