首页 > 解决方案 > 使用python按类成员对字典进行排序

问题描述

我有以下代码

class Test:
    def __init__(self,a ,b):
        self.a=a
        self.b=b
        
l= {}
myObj1 =Test(1,2) 
myObj2 =Test(3,4) 
l[1]=myObj1
l[2]=myObj2

如何按班级l成员对字典进行排序bTest

我已经尝试过l= sorted (l.items() , key = lambda x:x[1].b , reverse =True),但是当我尝试打印时print (l[1].b)出现错误

Traceback (most recent call last):
  File "l.py", line 13, in <module>
    print (l[1].b)
AttributeError: 'tuple' object has no attribute 'b'

所以我的排序损坏了我的列表。

标签: pythonpython-3.xsorting

解决方案


蟒蛇> = 3.7

d_unsorted = {1: Test(1,2), 2: Test(3,4), 3: Test(0,5), 4:Test(6,-1)}
d_sorted   = dict(sorted(d_unsorted.items(), key=lambda item: item[1].b))

参考:


推荐阅读