Python, Tk and OptionMenu: how to sort a drop down list?
The issue is that you're using a dictionary as a list, and dictionaries don't have any notion of order. Two ways you could do it; both are pretty straightforward.
Way 1: Just use sorted keys
You don't have to change much, just when you pass in lst1.keys()
, you instead pass in sorted(lst1.keys())
, since keys()
returns a list and you can give a sorted one of those.
Way 2: Use a dictionary that keeps order
One of the python standard libraries is collections
, which contains many containers of varying usefulness. One of these is the OrderedDict
, a dictionary that keeps the order in which you enter things. You would import it as from collections import OrderedDict
, and initialize it as any other object - lst1 = OrderedDict([("10us",0), ("20us",1), ...])