1

I have designed a menu and I'm using a dictionary for the values. I would like to stay with a dictionary if at all possible. The only problem is that a dictionary automatically shuffles its contents and I need it, quite obviously, to print the menu in the order I want. My code so far looks like this:

menu = {}
menu['1']="Encrypt message" 
menu['2']="Decrypt message"
menu['3']="Secure Encrypt Message"
menu['4']="Exit"
while True:
    for number, name in menu.items():
      print(number+")", name)
    selection=input("Please Select:") 

Any help would be greatly appreciated.

Matt123
  • 43
  • 1
  • 7

2 Answers2

1

Dictionary keys, by definition, are not in any particular order. You would either need some other structure to represent their order (like a list), or you could sort the keys (if there is an appropriate sort order).

You could also use an OrderedDict, if you want the keys in the order they were inserted.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

Dictionaries are unordered. You want a list or another ordered type.

menu = [
    "Encrypt message",
    "Decrypt message",
    "Secure Encrypt Message",
    "Exit",
    ]
for n, x in enumerate(menu, start=1):
    print("{}) {}".format(n, x))
selection = input("Please select: ")

Or perhaps you want to include a data item with your text labels:

menu = [
    # TODO: define your encrypt, decrypt and secure_encrypt functions
    ("Encrypt message", encrypt),
    ("Decrypt message", decrypt),
    ("Secure Encrypt Message", secure_encrypt),
    ("Exit", sys.exit),
    ]
for n, (label, _) in enumerate(menu, start=1):
    print("{}) {}".format(n, label))
selection = input("Please select: ")
assert 1 <= selection <= len(menu), "TODO: better error handling"
menu[selection - 1][1]()
Fred Nurk
  • 13,952
  • 4
  • 37
  • 63