gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:55:57 27 4
gpt4 key购买 nike

我想以属性排序的方式遍历对象字典

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' object has no attribute 'age'

最佳答案

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

关于python - 如何按属性值对对象字典进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052912/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com