从字典里取东西的更有效的方法

2024-03-28 10:44:06 发布

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

所以,我正在写一个程序,你可以输入关键字来取回一些东西,但是使用'if elif else'语句的方法似乎不是一个非常有效的方法。有更好的办法吗?以下是一些代码供参考:

things = {
    "word": "desc."
    #So on and so forth
}

def check():
    find = raw_input("> ")
    if find == "word":
        print things["word"]
        get_check()
    #So on and so forth with the elif's and else's
    elif find == "exit":
        print ""

def get_check():
    check()

check()

如果没有更有效的方法,请告诉我(我想会有,虽然。)另外,关于标题很抱歉,我不知道许多技术术语,我应该使用。所以请随意编辑标题


Tags: and方法ifsoondefcheckfind
2条回答
if find == 'exit':
  # Exit
else:
  item = things.get(find)
  if item is not None:
    # Do something with item
  else:
    # find not found

您可以使用in找出某个键是否在字典中:

if find in things:
    print things[find]

或者只使用^{}返回与键关联的值或None

print things.get(find)

相关问题 更多 >