Insert set values in same order they appear in code

Question:

All I want is insert to listbox items in the same order as in the set. I want it to be inserted like: ‘damp’->’camp’->’came’ and so on. How can I do that?

    gui_dict = tk.Listbox(third_task_window, width=10, height=10)
    words = {'damp', 'camp', 'came', 'lame', 'lime', 'like',
             'cold', 'card', 'cord', 'corm', 'worm', 'warm'}
    for word in words:
        gui_dict.insert(tk.END, word)
Asked By: Reboot

||

Answers:

you are putting them in a set {}, which sorts based on hash on creation, put them in a list [] instead and they won’t be sorted, they will be in the same order you put them in.

import tkinter as tk

root = tk.Tk()
gui_dict = tk.Listbox(root, width=10, height=10)
words = ['damp', 'camp', 'came', 'lame', 'lime', 'like',
         'cold', 'card', 'cord', 'corm', 'worm', 'warm']
for word in words:
    gui_dict.insert(tk.END, word)
gui_dict.pack()

root.mainloop()

see python data structures documentation : https://docs.python.org/3/tutorial/datastructures.html

Answered By: Ahmed AEK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.