[Tutor] omit some keys from dict

Sean 'Shaleh' Perry shalehperry@attbi.com
Thu, 07 Feb 2002 10:45:12 -0800 (PST)


On 15-Jan-2002 Karthik Gurumurthy wrote:
> I have a dict and i don't want to look for certain keys.
> "omit" lists the keys i want to omit.
> To get the remaining keys i can probably do this..
> 
> 
> j= {1:'hello',2:'fine',3:'python',4:'dicts',5:'lists',6:'tuples'} #actual
> dict
> omit = [1,3,5]
> checkkeys = [key for key in j.keys() if key not in omit]
> 
> Now how can i write this using *only* filter and lambda?
> 

>>> j= {1:'hello',2:'fine',3:'python',4:'dicts',5:'lists',6:'tuples'}
>>> omit = [1,3,5]
>>> filter(lambda key, omit = omit: key not in omit, j.keys())
[6, 4, 2]

That will work even under 1.5.2.  Under 2.1 and above the 'omit = omit' can be
left out.  If it were not for the need to place 'omit' in the scope of the
lambda I find the filter call much more readable.