Sort dictionary by value property

Viewed 244

How can the dictionary

class Foo:
    def __init__(self,value):
        self.property = value
        
dictionary = {"one":Foo(1),
              "two":Foo(2)}

be sorted in descending order, by the value of the Foo object's self.property?

2 Answers
sorted_dict = {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1].property)}

Easy - don't. A dictionary is a data structure which is designed to allow efficient association between the key and its value. As such, Python uses an ordering which facilitates that. If you need a sorted result, then select the values you need into a more appropriate structure (perhaps a list) and sort that.

Related