2

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?

Oblomov
  • 8,953
  • 22
  • 60
  • 106
  • Do you wanna print them sorted? Because you can't sort a dictionary. You access them by `key` and not by index. Am I right? – Jakub Szlaur Jan 24 '21 at 17:36
  • 1
    [check this post](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6). dictionaries in 3.6+ are insertion ordered – warped Jan 24 '21 at 17:36

2 Answers2

7
sorted_dict = {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1].property)}
Epsi95
  • 8,832
  • 1
  • 16
  • 34
3

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.

user2093190
  • 59
  • 1
  • 3