[英]Python: Checking if a key is part of a dictionary
我正在嘗試用Python制作自己的irc機器人(用於抽搐)。 我有一本命令字典:
commands = {
'!ping': {
'cooldown': 30,
'return': '!pong'
},
'!random': {
'cooldown': 30,
'return': 'command',
'argc': 2,
'arg_username': True,
'usage': '!random <min> <max>'
}
} # End of commands
然后,我有一個功能來檢查發送的消息是否確實是命令:
import string
def is_valid_command(command):
return True if command in commands.keys() else False
因此,當我測試此功能時,它似乎不起作用,並且我不知道自己在做什么錯:
message = "!ping"
print(str(is_valid_command(message)))
>>> False
我試圖將字典中的“!ping”更改為“!ping”,反之亦然,並刪除了該消息,甚至刪除了“!” 它總是說這是錯誤的。
謝謝,勞倫斯
編輯:
def is_valid_command(command):
for key in commands.keys():
print(key)
print("input " + str(command))
print(command in commands.keys())
return command in commands.keys()
結果是這樣的:
!ping
!random
input !ping
False
EDIT2:@ e4c5要我使用try / except,因為我快速嘗試了它(在該methode內部),它仍然返回False
try:
cmd = commands[command]
print ('Try True')
return True
except KeyError:
print('Try False')
return False
EDIT3:u'!ping'在解決此問題之前(消息= u'!ping'),但是當我從其他地方讀取字符串時,有沒有執行此unicoding的函數?
您的is_valid_command
函數可以簡化為:
def is_valid_command(command):
return command in commands
我剛剛測試了您的腳本,它似乎運行良好。
做了一些簡化,但是基本上與您具有相同的代碼。
commands = {
'!ping': {
'cooldown': 30,
'return': '!pong'
},
'!random': {
'cooldown': 30,
'return': 'command',
'argc': 2,
'arg_username': True,
'usage': '!random <min> <max>'
}
}
def is_valid_command(command):
return command in commands.keys()
print(is_valid_command("!ping"))
返回True
。 如果我嘗試命令!pong
則返回False
。
不需要此預檢查,並且是非Python的。 代替所有這些並發症,只需
try:
cmd = commands[message]
# do whatever with cmd
except KeyError:
print ('Sorry not a valid command')
尋求寬恕比允許容易。 這種通用的Python編碼風格假定有效鍵或屬性的存在,並且在假定被證明為假的情況下捕獲異常。 這種干凈快捷的樣式的特點是存在許多try和except語句。 該技術與許多其他語言(例如C)通用的LBYL風格形成對比。
您為什么不只返回:
return command in commands.keys()
那應該是對/錯了! 希望這個澄清!
如上所述,僅從您的消息中創建unicode字符串:
u'%s' % message
我正在使用python2.7,您的代碼為我返回True。
除了編寫函數,您可以直接使用:
message = "!ping" print(commands.has_key(message))
是的,有一個函數可以將字符串轉換為unicode。 使用unicode
函數,例如unicode('my_string')
。
例如,如果來自irc的消息存儲在變量message_from_irc
則可以將其轉換為unicode(message_from_irc)
。
我建議您在編碼時將鍵盤語言切換為英語,以避免此類意外的代碼行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.