paramikoooo
paramikoooo

Reputation: 178

sort dictionary by member of class with python

I have the following code

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

How can I sort the dictionary l by the member b in class Test

I have tried l= sorted (l.items() , key = lambda x:x[1].b , reverse =True) but then when I tried to print print (l[1].b) I got error

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

So my sorted damage my list .

Upvotes: 0

Views: 168

Answers (1)

Stef
Stef

Reputation: 15505

Python >= 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))

References:

Upvotes: 1

Related Questions