30
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.

1
  • 3
    It's worth noting that putting spaces between the = and an argument is against PEP-8's recommendations. Commented Mar 29, 2013 at 22:16

1 Answer 1

66

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])
Sign up to request clarification or add additional context in comments.

7 Comments

Why was this syntax removed?
@Blender It was shown to be little used, and made things like function annotations awkward, as well as adding complexity to some introspection stuff. It's also very easily replaced. See PEP-3113.
Thank you so much! this works perfectly. Also, not that it matters, but would you happen to know why I had to change iteritems() to items() to run it with python3 as well?
@Zack iteritems() was there as items() in 2.x returns a list, which is memory-inefficient. In 3.x, items() returns an iterator, removing the need for iteritems().
@NarenBabuR That lambda would require two different arguments when called, not a single tuple.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.