如何停止字典改组? (Python)

How to stop a dictionary shuffling? (Python)

我设计了一个菜单,并使用字典作为值。如果可能的话,我想留下一本字典。唯一的问题是字典会自动打乱其内容,很明显,我需要它来按我想要的顺序打印菜单。到目前为止,我的代码如下所示:

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:") 

如有任何帮助,我们将不胜感激。

根据定义,字典键没有任何特定顺序。您可能需要一些其他结构来表示它们的顺序(如列表),或者您可以对键进行排序(如果有适当的排序顺序)。

如果您希望密钥按插入顺序排列,您也可以使用 OrderedDict

字典是无序的。您需要列表或其他有序类型。

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: ")

或者您可能希望在文本标签中包含一个数据项:

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]()