Reputation: 11683
d = {'foo': 'x',
'bar': 'y',
'zoo': 'None',
'foobar': 'None'}
I want to filter all the items whose value is 'None'
and update the foo
and bar
items with a particular value. I tried:
for i in x.items():
....: if i[i] == 'None':
....: x.pop(i[0])
....: else:
....: x.update({i[0]:'updated'})
But it is not working.
Upvotes: 10
Views: 27607
Reputation: 28703
It is not clear what is 'None'
in the dictionary you posted. If it is a string, you can use the following:
dict((k, 'updated') for k, v in d.items() if v != 'None')
If it is None
, just replace the checking, for example:
dict((k, 'updated') for k, v in d.items() if v is None)
(If you are still using Python 2, replace .items()
with .iteritems()
)
Upvotes: 22
Reputation: 8010
You could try writing a general filter function:
def filter(dict, by_key = lambda x: True, by_value = lambda x: True):
for k, v in dict.items():
if (by_key(k) and by_value(v)):
yield (k, v)
or
def filter(dict, by_key = lambda x: True, by_value = lambda x: True):
return dict((k, v) for k, v in dict.items() if by_key(k) and by_value(v))
and then you can do this:
new_d = dict(filter(d, by_key = lambda k: k != 'None'))
Note that this was written to be compatible with Python 3. Mileage may vary.
The cool thing about this is that it allows you to pass arbitrary lambdas in to filter instead of hard-coding a particular condition. Plus, it's not any slower than any of the other solutions here. Furthermore, if you use the first solution I provided then you can iterate over the results.
Upvotes: 1
Reputation: 320019
it's not clear where you're getting your 'updated'
value from, but in general it would look like this:
{i: 'updated' for i, j in d.items() if j != 'None'}
in python2.7 or newer.
Upvotes: 15
Reputation: 21065
new_d = dict((k, 'updated') for k, v in d.iteritems() if k != 'None')
Upvotes: 0
Reputation: 47672
Something like this should work
>>> for x in [x for x in d.keys() if d[x] == 'None']:
d.pop(x)
Upvotes: 2