Search code examples
pythonsortingdictionaryordereddictionary

Sorting dict() on field of class


I have a dictionary with objects as values. These objects are instances of the following class:

Class A():

    def __init__(self, x=''):
        self.x = x
        self.count = 0

The dictionary entries will therefore be of the form: {'some_key', instance_of_class_A}

Now, I would like to sort the dictionary on the the value of A.count within the instance_of_A.

I have failed to find an answer to this through numerous searches so am hoping someone has solved this before! Thanks P.


Solution

  • To sort the values of a dictionary, you can do the following:

    sorted_values = sorted(dict.values(), key=lambda x: x.count)
    

    I do not see the need for sorting an entire dictionary, however. If the key value can hold a list of A objects and you want to sort that:

    dict[key] = sorted(dict[key], key=lambda x: x.count)