0

I am creating a simple GUI application to manage unknown words while learning a new language. Nevertheless, I have a list which I am trying to sort alphabetically, from A to Z:

def sort_words(self):
    sorted_words = sorted(self.words)

    self.listBox.delete(0, END)
    for item in sorted_words:
        self.listBox.insert(END, item.wordorphrase)

The problem is I am getting:

/usr/bin/python3.5 /home/cali/PycharmProjects/Vocabulary/Vocabulary.py
Traceback (most recent call last):
  File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 361, in <module>
    main()
  File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 355, in main
    gui = Vocabulary(root)
  File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 28, in __init__
    self.load_words()
  File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 153, in load_words
    self.sort_words()
  File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 156, in sort_words
    sorted_words = sorted(self.words)
TypeError: unorderable types: Word() < Word()

Process finished with exit code 1

Note that it's a list of Word objects, not strings.

How can I sort my words?

  • 2
    Define your Word class with the appropriate special methods so Python knows how to sort them; Possible duplicate of [Making a python user-defined class sortable, hashable](http://stackoverflow.com/questions/7152497/making-a-python-user-defined-class-sortable-hashable) , also http://stackoverflow.com/questions/4630341/how-to-make-sortable-datatype-in-python, http://stackoverflow.com/questions/16955001/how-to-make-class-data-sortable, – TessellatingHeckler Apr 19 '17 at 04:59

1 Answers1

3

Try sorted(self.words, key=str), it should compare your words as a strings.

It works only if you defined __str__ method for word (or __unicode__ in case of python2). If you didn't, use next lambda:

sorted(self.words, key=lambda word: word.attr_where_you_store_actual_string)

Bakuutin
  • 301
  • 1
  • 9