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

时间:2022-07-03 18:33:17

I would like to iterate over a dictionary of objects in an atribute 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 eror message: "AttributeError: 'str' object has no attribute 'age'"

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

4 个解决方案

#1


11  

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

#2


4  

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

#3


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

source: https://wiki.python.org/moin/HowTo/Sorting

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

#4


-1  

How is showed in the documentation of sorted method

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

sorted(student_Dict.keys(), key=lambda student: student.age)

#1


11  

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

#2


4  

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

#3


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

source: https://wiki.python.org/moin/HowTo/Sorting

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

#4


-1  

How is showed in the documentation of sorted method

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

sorted(student_Dict.keys(), key=lambda student: student.age)