[Tutor] omit some keys from dict

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 7 Feb 2002 19:58:34 +0100

On  0, Sean 'Shaleh' Perry <shalehperry@attbi.com> wrote:
> >>> 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.

Right, I left out the 'omit = omit' because I'm used to 2.1 code. 2.1 is
about ten months old; 1.5.2 about three years. All my thesis code is 2.1
style code. I expect that most newbies have downloaded Python recently. So
I'm not posting legacy code anymore unless there's a specific reason for it.

My personal guidelines for using filter/map/lambda:

I like filter better if it is a 'pure filter', like the one above.
The expression in the list comprehension is just the variable - 
[x for x in xs if ...].

I like map if and only if the function already exists and a lambda isn't
necessary - map(str, range(10)).

If the situation is even a little more complex than this, I prefer the list
comprehension. [str(i)+"%" for i in range(10)] instead of 
map(lambda i: str(i)+"%", range(10)).

Remco Gerlich