如何检查字典中的项目是否为Python中的变量?

2024-10-01 19:34:32 发布

您现在位置:Python中文网/ 问答频道 /正文

cheats = {
            "GODMODE" : "Health and armour + 1000",
            "Full pockets" : "adds 1000 of each item",
            }
commands = {
             "cheats" : "show cheats",
             "activate [cheat]" : "activates a cheat",
             }
command = input(">").split()
if len(command) == 0:
    continue

if len(command) > 0 :
    verb = command[0].lower()

if len(command) >1 :
    item = command[1].lower()

if user_input = "activate" :
    if item in cheats:

如何检查用户想要激活的欺骗?其他的一切都是有效的。它是更大一部分代码的一部分


Tags: andinputlenifitemlowercommandfull
3条回答

我相信你在找cheats.keys()。它返回字典键的元组

您只需从字典或None中提取相关值(如果不存在)

这假设您不想做任何事情,除非您得到如下形式的输入:activate cheatcode

cheats = {
        "GODMODE" : "Health and armour + 1000",
        "Full pockets" : "adds 1000 of each item",
        }
ask  = input("what do you wish to do?")
code = ask.split()[1]
activate = cheats.get(code,None)
#do something based on activate value

Activate现在选择了cheat的值或None。不需要循环或条件,除非您想允许同时启用多个欺骗

我将使用try...except块:

if user_input == 'activate':
   try: 
       activate(cheats[item])   # or whatever
   except KeyError:
       print("bad cheat")

相关问题 更多 >

    热门问题