How to filter a dictionary in Python?

Question:

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.

Asked By: user426795

||

Answers:

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.

Answered By: SilentGhost
new_d = dict((k, 'updated') for k, v in d.iteritems() if k != 'None')
Answered By: Rosh Oxymoron

Something like this should work

>>> for x in [x for x in d.keys() if d[x] == 'None']:
        d.pop(x)
Answered By: ismail

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())

Answered By: khachik

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.

Answered By: Woody1193
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.