0

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 .

paramikoooo
  • 177
  • 2
  • 16
  • Use a combination of [How do I sort a dictionary by value?](https://stackoverflow.com/a/613218/3080723) and [Sort a list of tuples by 2nd item value](https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value) – Stef Dec 07 '20 at 10:14
  • Actually the second link should be [How to sort a list of objects based on an attribute of the objects](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects), not the "tuple by second value" link. – Stef Dec 07 '20 at 10:23
  • The error you get is because `sorted` returns a `list`, not a `dict`. – Stef Dec 07 '20 at 10:26

1 Answers1

1

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:

Stef
  • 13,242
  • 2
  • 17
  • 28