Remove multiple values ​​from python [list] dictionary

I try to remove all values 'x'from a large dictionary and DO NOT delete any keys, but when I run the code, the 'x'values still remain .

Here is an excerpt from my dictionary:

myDict = {0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2', 'x', 'x'], 2: ['id1', 'x', 'x', 'x']} 

My code is:

for k, v in myDict.iteritems():
if v == 'x':
    myDict.remove('x')
print myDict

What am I striving for:

myDict = {0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2'], 2: ['id1']}

How can I remove the values 'x'in the lists, please?

+4
source share
4 answers

You can use list comprehension in 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']}
+4
source

Just do the following:

for key in myDict:
    while 'x' in myDict[key]:
        myDict[key].remove('x')

, .remove() , . while, , .remove() . , .

+2

:

  • remove , , .

  • remove.

  • v == 'x' , 'x', True, , 'x'.

  • remove 'x'.

- :

>>> {k:[x for x in v if x!='x'] for k,v in myDict.iteritems()}
{0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2'], 2: ['id1']}

:

>>> for k,v in myDict.iteritems():
...     myDict[k] = [x for x in v if x!='x']
... 
>>> myDict
{0: ['id1', 'id2', 'id3'], 1: ['id1', 'id2'], 2: ['id1']}

, , filter. -:

>>> filter(lambda x: x!='x', ['id1', 'x', 'x', 'x'])
['id1']
+2

For python2 just do:

for k, v in myDict.iteritems():
    if v == 'x':
        myDict[k].remove('x')

The problem was that you called the method removefrom dict instead of the dict element (myDict [k]]

I think you are in Python2 since you are using iteritems (). For python 3, you can do this with dict concepts that are not available for version 2.

+1
source

All Articles