Decision
Starting with python 2.7, you can use dictionary comprehension. There are similar views, but apply to the dictionary:
>>> parent_dict = {1: 'Homer', ... 2: 'Bart', ... 3: 'Lisa', ... 4: 'Marge', ... 5: 'Maggie' ... } >>> {key:val for key,val in parent_dict.iteritems() if 2 < key < 4 } 1: {3: 'Lisa'}
You probably don't need to make it a function, but if you do, you can just use the lambda function as a filter:
>>> def filter_func(somedict, key_criteria_func): ... return {k:v for k, v in somedict.iteritems() if key_criteria_func(k)} ... ... filter_func(parent_dict, lambda x: 2 < x < 4) 2: {3: 'Lisa'}
For Python 2.6.5 and the entire version prior to 2.7, replace the dict understanding as follows:
dict((k,v) for k,v in parent_dict.iteritems() if 2 < k < 4)
Why is lambda function?
The lambda function is not magical, it's just a way to easily create a background on the fly. You can do everything you do with lambda without it, the only difference is that lambdas are an expression, and therefore they can be used directly between parenthis.
For comparison:
>>> func = lambda x: 2 < x < 4 >>> func(3) True
WITH
>>> def func(x): ... return 2 < x < 4 ... >>> func(3) True
This is exactly the same and creates the same function, except that the lambda function will not have a name. But you don’t care, in your case you don’t need a name, you just need a link to call it, and the func variable contains that link.
The lambda syntax looks weird because:
- You don't need parentheses for parameters (you don't even need a parameter)
- you are not doing
def var(param): but var = lambda param: Nothing magical, it's just the syntax - you cannot make 2 lines of
lambda : the return result must match one instruction. - you are not using the
return keyword: the right side of the lambda returns automatically
Now the nice thing with lamda is that since this is an expression, you can use it between parenthese, that is, you can create and transfer your image at the same time.
For comparison:
>>> filter_func(parent_dict, lambda x: 2 < x < 4)
WITH
>>> def func(x): ... return 2 < x < 4 ... >>> filter_func(parent_dict, func)
This is exactly the same. The lambda is shorter.
The tough part here is to understand that you can pass a function as a parameter in Python, because everything in Python is an object, including functions.
You can even do this:
>>> def func(): ... print "test" ... >>> ref_to_func = func
And you can even define fonction on one line:
>>> def func(): print "test" >>> func() test
But you cannot do this:
filter_func(parent_dict, def func(x): 2 < x 4 )
This is where lambdas are useful.