Tôi muốn để lặp qua một cuốn từ điển của các đối tượng trong một atribute được sắp xếp cáchLàm thế nào để sắp xếp các từ điển của các đối tượng theo giá trị thuộc tính trong python?
import operator
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
studi1=Student('john', 'A', 15)
studi2=Student('dave', 'B', 10)
studi3=Student('jane', 'B', 12)
student_Dict = {}
student_Dict[studi1.name]=studi1
student_Dict[studi2.name]=studi2
student_Dict[studi3.name]=studi3
for key in (sorted(student_Dict, key=operator.attrgetter('age'))):
print(key)
này mang lại cho tôi được thông báo eror: "AttributeError: đối tượng 'str' không có thuộc tính 'tuổi'"
Cảm ơn các bạn, nhận xét của Karl Knechtel là đúng. Tôi đã không suy nghĩ về điểm này. Vì vậy, cả hai câu trả lời (Nolen Royalty và Dugres) là chính xác. – Fienchen21
Điều đó tiết kiệm rất nhiều thời gian của tôi – Sakeer