如何在python根据属性值的对象字典排序? [英] How to sort dictionaries of objects by attribute value in python?

查看:336
本文介绍了如何在python根据属性值的对象字典排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历对象字典在属性附加伤害排序方式

 进口经营者类学生:
        高清__init __(自我,姓名,年级,年龄):
                self.name =名称
                self.grade =等级
                self.age =年龄
studi1 =学生('约翰','A',15)
studi2 =学生('大卫','B',10)
studi3 =学生('简','B',12)student_Dict = {}
student_Dict [studi1.name] = studi1
student_Dict [studi2.name] = studi2
student_Dict [studi3.name] = studi3在(排序(student_Dict,键= operator.attrgetter('年龄')))键:
    打印(键)

这给了我eror消息:AttributeError的:'海峡'对象没有属性'年龄'。


解决方案

 为学生(排序(student_Dict.values​​(),键= operator.attrgetter('年龄'))) :
    打印(student.name)

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'"

解决方案

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

这篇关于如何在python根据属性值的对象字典排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆