filter()ing a dict

Robin Cull robin.cull at pace.co.uk
Fri Aug 8 05:10:03 EDT 2003


robin.cull at pace.co.uk (Robin Cull) wrote in message news:<16469f07.0308070559.aed41a at posting.google.com>...
<SNIP>
>  
> I can write something to get around the behaviour in this particular
> case (although suggestions would be welcome).
>
<SNIP>

Thanks all for your explanations and examples.  I quite like the list
comprehension methods.  I didn't comprehend (pun intended) what list
comprehensions were until I saw these examples so I've learnt
something new! :)

For my particular script, which is likely to be used by pythonistas
even less experienced than me, I decided to solve the problem this
way:

def filterDict(testFunction, dictToFilter):
    newDict = {}
    for k, v in dictToFilter.items():
        if testFunction(v):
            newDict[k] = v
    return newDict

Seems to work for what I want it to do and since it's a standalone
defined function which mimics filter() should be nice and easy to
understand for people who have to look at it later.

I appreciate all your replies.  

Regards, 

Robin




More information about the Python-list mailing list