Python Forum

Full Version: lambda function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, 

I have the following code:

from collections import OrderedDict
tallyDict = {'New York': 12, 'Boston': 32, 'Atlanta': 5, 'Los Angeles': 16, 'Miami': 21}
tallySorted = OrderedDict(sorted(tallyDict.items(), key=lambda t: t[1], reverse=True))
the part key=lambda t: t[1].

1) What does "t" here references?
I assume that "t" references tallyDict.items(). the square brackets in t[1] seems referencing list but type(tallyDict.items()), I got <class 'dict_items'>. So I'm a little confused here what "t" references.

2) Is there a technique that I could use to figure out myself what "t" in this lambda function references?

Thank you!
The key function is passed each item of the sequence it is sorting.
In this case you are passing it the items() of a dict.
This is a sequence of (key, value) tuples like ('New York', 12).

So the argument t is one of these tuples and t[1] is the second element of the tuple.

IE you are sorting by the numbers and then reversing it.

Clear?
Understood.

Thank you!
lambda is just a short way of defining a function.  If you want a better idea of how it's called, use a better function :P
Here's an example, showing how you can figure out what the arguments are:
from collections import OrderedDict


def test_sort(*args):
   print(args)
   return 1


tallyDict = {'New York': 12, 'Boston': 32, 'Atlanta': 5, 'Los Angeles': 16, 'Miami': 21}
tallySorted = OrderedDict(sorted(tallyDict.items(), key=test_sort, reverse=True))
And the output is:
Output:
(('Miami', 21),) (('Boston', 32),) (('Los Angeles', 16),) (('New York', 12),) (('Atlanta', 5),)
So, one argument is passed, and it's a tuple of (key, value).  So in your lambda, when you return "t[1]", you're returning the second item in that tuple, which is... whatever number that represents for the city name.

Another way to test it out, is to see what some_dict.items() gives...
tallyDict = {'New York': 12, 'Boston': 32, 'Atlanta': 5, 'Los Angeles': 16, 'Miami': 21}
for thing in tallyDict.items():
   print(thing)
Output:
('Los Angeles', 16) ('Boston', 32) ('New York', 12) ('Miami', 21) ('Atlanta', 5)
When you saw " <class 'dict_items'>", that's because the items aren't actually calculated until they're needed, as it's lazy and only does work when you need it.  So looping over the values lets us see what they are.