Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a dictionary in Python?

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.

like image 931
user426795 Avatar asked Dec 19 '10 19:12

user426795


People also ask

Can I filter a dictionary in Python?

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 .

How do I filter a dictionary list in Python?

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 .

Can I sort dictionary in Python?

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.


2 Answers

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)
like image 163
khachik Avatar answered Sep 28 '22 10:09

khachik


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.

like image 27
SilentGhost Avatar answered Sep 28 '22 12:09

SilentGhost