I was trying to use the orderedDict module to sort my dictionary but came up with this question while looking at some example code like below:
# regular unsorted dictionary
d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
# dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
So what confused me in the code is the Lambda function used inside sorted() function. I understand that 't' is the argument and 't[0]' or 't[1]' are the expression but can't figure out how 't' get assigned value inside the sorted(). In the code it seems like 't = d.items()' happens automatically?
Please help me to understand the mechanism here and thanks a lot in advance!