Paul
Paul

Reputation: 982

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.

Upvotes: 3

Views: 411

Answers (3)

jpp
jpp

Reputation: 164663

While dictionaries are insertion-ordered in Python 3.6 (as an implementation detail) and officially in 3.7+, for a robust ordered dictionary use collections.OrderedDict:

from collections import OrderedDict

res = OrderedDict(sorted(d.items(), key=lambda x: x[1].count))

OrderedDict is a subclass of dict, so you should lose no functionality.

If such an ordering is natural or typical to your class objects, consider defining __eq__ and __lt__ methods to your class as described here and then use:

from operator import itemgetter

res = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
res = OrderedDict(sorted(d.items(), key=itemgetter(1)))  # functional equivalent

Upvotes: 1

chepner
chepner

Reputation: 531085

Assuming you are using a version of Python that provides for guaranteed ordering, you need to create a new dict, inserting the elements in the proper order.

old_dict = { ... }
new_dict = dict(sorted(old_dict.items(), key=lambda kv: kv[1].count))

Upvotes: 1

SBylemans
SBylemans

Reputation: 1764

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)

Upvotes: 2

Related Questions