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.
Filter Python Dictionary By Key Using Generic Function The lambda function you pass returns k%2 == 1 which is the Boolean filtering value associated with each original element in the dictionary names .
Solution: Use list comprehension [x for x in lst if condition(x)] to create a new list of dictionaries that meet the condition. All dictionaries in lst that don't meet the condition are filtered out. You can define your own condition on list element x .
Using the sorted() Function The critical function that you'll use to sort dictionaries is the built-in sorted() function. This function takes an iterable as the main argument, with two optional keyword-only arguments—a key function and a reverse Boolean value.
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.iteritems() if v != 'None')
If it is None
, just replace the checking, for example:
dict((k, 'updated') for k, v in d.iteritems() if v is None)
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.
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