Using a lambda with sorted function

I came across the following code and it is working fine.Though I looked for lambda functions in other questions , but did not find a relevant answer

In[9]: portfolio=[
                    {'name': 'IBM', 'shares': 100, 'price': 91.1},
                    {'name': 'IAM', 'shares': 100, 'price': 41.1},
                    {'name': 'IBM', 'shares': 100, 'price': 71.1} ,
                    {'name': 'IBM', 'shares': 100, 'price': 31.1} 
          ]
In [10]: s =  sorted(portfolio,key = lambda s : s['price'] )
Out[10]: s
[{'name': 'IBM', 'price': 31.1, 'shares': 100},
 {'name': 'IAM', 'price': 41.1, 'shares': 100},
 {'name': 'IBM', 'price': 71.1, 'shares': 100},
 {'name': 'IBM', 'price': 91.1, 'shares': 100}]

Questions:

  1. Is lambda function called to return the price every time a dictionary element is called from the list ? lambda is called only once ?
  2. If can anyone explain this whole of how the sorted works here, it will be very helpful

1 answer

  • answered 2017-06-17 19:46 Hugh Bothwell

    Well, let's try it:

    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'IAM', 'shares': 100, 'price': 41.1},
        {'name': 'IBM', 'shares': 100, 'price': 71.1} ,
        {'name': 'IBM', 'shares': 100, 'price': 31.1} 
    ]
    
    def key_fn(s):
        print("called key_fn({})  ->  {}".format(s, s['price']))
        return s['price']
    
    s = sorted(portfolio, key=key_fn)
    

    which produces

    called key_fn({'shares': 100, 'price': 91.1, 'name': 'IBM'})  ->  91.1
    called key_fn({'shares': 100, 'price': 41.1, 'name': 'IAM'})  ->  41.1
    called key_fn({'shares': 100, 'price': 71.1, 'name': 'IBM'})  ->  71.1
    called key_fn({'shares': 100, 'price': 31.1, 'name': 'IBM'})  ->  31.1
    

    Conclusion: the key function is called once per item being sorted.