如何在python中按属性值对对象的字典进行排序?

时间:2012-04-07 08:15:59

标签: python dictionary attributes operator-keyword sorted

我想以属性排序方式迭代对象字典

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)

这给了我错误消息:“AttributeError:'str'对象没有属性'age'”

4 个答案:

答案 0 :(得分:14)

for student in (sorted(student_Dict.values(), key=operator.attrgetter('age'))):
    print(student.name)

答案 1 :(得分:5)

>>> for key in sorted(student_Dict, key = lambda name: student_Dict[name].age):
...     print key
... 
dave
jane
john

答案 2 :(得分:1)

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))


student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
print student_objects
student_objects.sort(key=attrgetter('age'))
print student_objects

来源:https://wiki.python.org/moin/HowTo/Sorting

答案 3 :(得分:-1)

如何在sorted方法

的文档中显示
sorted(student_Dict.keys(), key=lambda student: student.age)