0

I have a dictionary that has company names as keys. The values are a namedtuple of two things. entity having a link to company url and grade having a numerical value. I would like to sort this dictionary based on value and specifically by grade. I am trying to use key function as key=lambda (k,v):v.grade. But I am getting an error pointed at the bracket next to lambda keyword. Code snippet is below. Can anyone please help?

sorted_dict = sorted(list(dict_interested_companies.items()), key=lambda (k,v):v.grade)

For example, Display values of dict.items()

[('Google', named_tuple(entity='http://money.cnn.com/video/technology/2018/02/01/kevin-abosch-i-am-a-coin.cnnmoney/index.html', grade=45)), ('Comcast', named_tuple(entity='http://money.cnn.com/2018/02/02/pf/college/public-service-student-loan-forgiveness/index.html', grade=39))

Bharath Bharath
  • 45
  • 1
  • 1
  • 10

2 Answers2

0

The key function is not supposed to take two arguments. It's always going to take one argument. It just so happens that in this case the argument is a 2-tuple, but it's still one argument.

# This is a function taking two arguments,
# *not* a function taking a tuple.
lambda k, v: v.grade

# This is equivalent to the above in Python
# 2 but has been disallowed in Python 3. Don't
# use this syntax; it's not portable.
lambda (k, v): v.grade

# This is a function taking one argument, a tuple,
# and using its second element. This is what you want.
lambda x: x[1].grade
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

If you want to avoid using a numeric index, you can use a nested lambda and upacking:

from collections import namedtuple

named_tuple = namedtuple('named_tuple', ['entity', 'grade'])

dict_interested_companies = {
    'Google': named_tuple(entity='http://money.cnn.com/video/technology/2018/02/01/kevin-abosch-i-am-a-coin.cnnmoney/index.html', grade=45),
    'Comcast': named_tuple(entity='http://money.cnn.com/2018/02/02/pf/college/public-service-student-loan-forgiveness/index.html', grade=39)
}

sorted_list = sorted(dict_interested_companies.items(), key=lambda item: (lambda key, value: value.grade)(*item))

print(sorted_list)

OUTPUT

[('Comcast', named_tuple(entity='http://money.cnn.com/2018/02/02/pf/college/public-service-student-loan-forgiveness/index.html', grade=39)), ('Google', named_tuple(entity='http://money.cnn.com/video/technology/2018/02/01/kevin-abosch-i-am-a-coin.cnnmoney/index.html', grade=45))]
cdlane
  • 40,441
  • 5
  • 32
  • 81