python-sortedcontainers
python-sortedcontainers copied to clipboard
Would it be possible to specify an attribute as the key to compare?
trafficstars
I would like to use instances of a class as the keys and to sort the instances according to an attribute, but I don't know how to do that. The lambda function seems not to work. Could anyone help me?
The following is an example.
from sortedcontainers import SortedDict
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
student1 = Student('john', 'A', 15)
student2 = Student('jane', 'B', 12)
sd = SortedDict(key=lambda student: student.age) # I would like to sort according to age
sd[student1] = 1 # This line returns an error: '<' not supported between instances of 'Student' and 'str'
sd[student2] = 2
print('sd:', sd)
I think you should use the age to be the key and the student to be the value.
sd = SortedDict()
sd[students1.age] = student1
sd[student2.age] = student2
Review this section of the introduction for help: https://grantjenks.com/docs/sortedcontainers/introduction.html#caveats There’s a very similar example there.