python-sortedcontainers icon indicating copy to clipboard operation
python-sortedcontainers copied to clipboard

Would it be possible to specify an attribute as the key to compare?

Open pengdlzn opened this issue 3 years ago • 2 comments
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)

pengdlzn avatar Mar 18 '22 09:03 pengdlzn

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

SakigamiYang avatar May 02 '22 10:05 SakigamiYang

Review this section of the introduction for help: https://grantjenks.com/docs/sortedcontainers/introduction.html#caveats There’s a very similar example there.

grantjenks avatar May 02 '22 14:05 grantjenks