0

I am new to python programming. I have come across this line of codes to sort a dict by value (Python 2.4 or greater):

for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)): print "%s: %s" % (key, value)

Please help me to understand the utility of using a function(here lambda function) inside another function using argument 'key'.

Thanks in advance!

1
  • you may want different results when using sorted: most common uses are ascending and descending order. in your example you are sorting a dictionary, for which ascending and descending doesn't mean anything. the lambda gives sorted the power to sort anything, the way you want Commented Jun 7, 2018 at 9:58

1 Answer 1

1

sorted's key attribute work as described bellow:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

sorted call key's function on each item within the dict to compute sorted output.

The utility is to let user to define complex sorting mechanisms.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.