23

I would like to iterate over a dictionary of objects in an attribute sorted way

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)

This gives me the error message: AttributeError: 'str' object has no attribute 'age'

4

4 回答 4

23
for student in (sorted(student_Dict.values(), key=operator.attrgetter('age'))):
    print(student.name)
于 2012-04-07T08:23:39.743 回答
8
>>> for key in sorted(student_Dict, key = lambda name: student_Dict[name].age):
...     print key
... 
dave
jane
john
于 2012-04-07T08:35:08.733 回答
0
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

于 2014-04-08T12:53:24.290 回答
0

如何在排序方法的文档中显示

sorted(student_Dict.keys(), key=lambda student: student.age)
于 2012-04-07T08:20:09.580 回答