How to filter a dictionary in Python?

d = {'foo': 'x', 'bar': 'y', 'zoo': 'None', 'foobar': 'None'} 

I want to filter out all elements whose value is 'None' and update the elements foo and bar with a specific value. I tried:

 for i in x.items(): ....: if i[i] == 'None': ....: x.pop(i[0]) ....: else: ....: x.update({i[0]:'updated'}) 

But it does not work.

+8
python dictionary
source share
4 answers

It is not clear that there is a 'None' in the dictionary that you posted. If it is a string, you can use the following:

 dict((k, 'updated') for k, v in d.iteritems() if v != 'None') 

If it is None , just replace the check, for example:

 dict((k, 'updated') for k, v in d.iteritems() if v is None) 
+17
source share

it's not clear where you get your 'updated' value from, but overall it will look like this:

 {i: 'updated' for i, j in d.items() if j != 'None'} 

in python2.7 or later.

+12
source share

Something like this should work

 >>> for x in [x for x in d.keys() if d[x] == 'None']: d.pop(x) 
+2
source share
 new_d = dict((k, 'updated') for k, v in d.iteritems() if k != 'None') 
0
source share

Source: https://habr.com/ru/post/650295/


All Articles