Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.2 Lambda Syntax Error [duplicate]

def sort_dictionary( wordDict ):     sortedList = []     for entry in sorted(wordDict.iteritems(), key = lambda (k, v): (-v, k) ):         sortedList.append( entry )      return sortedList 

The function would be receiving a dictionary containing information such as: { 'this': 1, 'is': 1, 'a': 1, 'large': 2, 'sentence': 1 } I would like to have it generate a list of lists, with the elements ordered first by the dictionary's values from Largest to Smallest, then by the keys alphabetically.

The function works fine when run with python 2.7.2, but I receive the error:

  File "frequency.py", line 87     for entry in sorted(wordDict.iteritems(), key = lambda (k, v): (-v, k)):                                                            ^ SyntaxError: invalid syntax 

when I run the program with python 3.2.3. I have been searching all over for a reason why, or syntax differences between 2.7 and 3.2, and have come up with nothing. Any help or fixes would be greatly appreciated.

like image 387
Zack Avatar asked Mar 29 '13 22:03

Zack


People also ask

Can Lambda take two arguments?

A lambda function can take any number of arguments, but can only have one expression.

Can lambda function be reused in Python?

Can we reuse the lambda function? I guess the answer is yes because in the below example I can reuse the same lambda function to add the number to the existing numbers.

Can Lambda take two arguments Python?

Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).

What are the limitations of lambda function in Python?

Cons on lambda functions:Lambda functions can have only one expression. Lambda functions cannot have a docstring. Many times lambda functions make code difficult to read. For example, see the blocks of code given below.


1 Answers

Using parentheses to unpack the arguments in a lambda is not allowed in Python3. See PEP 3113 for the reason why.

lambda (k, v): (-v, k) 

Instead use:

lambda kv: (-kv[1], kv[0]) 
like image 60
unutbu Avatar answered Sep 27 '22 18:09

unutbu