I believe this'll do the trick, but I can't test it without your actual dictionary and the objects. I suggest providing a sample of your data.
sorted_keys = sorted(file_dict, key=lambda k: file_dict[k].get_word_count())
sorted_file_dict = {k: file_dict[k] for k in sorted_keys}
Also, "sorting" a dictionary is a bit unnecessary. The whole point is that objects are able to be looked up via a hashtable, negating the need for any sort of ordering. If you want some kind of ordering while iterating, then you can iterate over the sorted keys. But a dictionary itself doesn't really need to be sorted, in most cases.
Closure edit: I disagree with closing this as a duplicate, since implementing __lt__
for the text_object
class still won't help you sort a dictionary of text_object
instances. Also, heads up, class names are conventionally CamelCase, consider renaming text_object
to TextObject
.
Addressing __lt__()
Since this question may not be reopened, I'll address how OP might use the information in the duplicate. To be honest, there isn't much of a difference in the end product, BUT it may not be the worst idea to implement it anyway:
class TextObject:
# attributes and methods, etc
def get_word_count(self):
return self.word_count
def __lt__(self, other):
return self.get_word_count() < other.get_word_count()
Then, in order to "sort" your dictionary:
sorted_keys = sorted(file_dict, key=lambda k: file_dict[k])
sorted_file_dict = {k: file_dict[k] for k in sorted_keys}
Notice that the only difference is that the sorted()
key function is no longer directly calling TextObject.get_word_count()
.
As others have mentioned, this method may be ideal for you if you're planning to do things like some_text_object < other_text_object
.
PS - you may want to look into the @property
decorator.