filter()ing a dict

Sean Ross sross at connectmail.carleton.ca
Fri Aug 8 16:33:18 CEST 2003


"Robin Cull" <robin.cull at pace.co.uk> wrote in message
news:16469f07.0308080110.6a9ef7a0 at posting.google.com...
> robin.cull at pace.co.uk (Robin Cull) wrote in message
news:<16469f07.0308070559.aed41a at posting.google.com>...
> 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 actually find the following version atleast as easy to understand as the
version above, but I perhaps I lack perspective.

def filterdict(predicate, mapping):
    "predicate() must take one (key,value) tuple as argument and return a
boolean"
    return dict(filter(predicate, mapping.iteritems()))

# useage:
fd = filterdict(lambda item: len(item[1])==4, d)






More information about the Python-list mailing list