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

标签 python sorting dictionary attributes

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

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/

相关文章:

iphone - 按字母顺序排列数组

c# - 尝试 C# 将 Json 解析为带有内部数组的字典

python - Django unique_together 不起作用 : "refers to the non-existent field"

python - SQLAlchemy 在执行查询中缓存 now()

python - 与python中的getattribute和setattribute混淆

php - 按最新日期排序文件在顶部使用 RecursiveDirectoryIterator

c# - Wpf 数据网格 : how to detect the set of visible cells?

python - 从 MATLAB 到 Python 的二维 FFT

python - 带有转义字符的 json.loads

python - 在 pyparsing 表达式中省略 setResultsName