简体   繁体   English

Python:检查键是否是字典的一部分

[英]Python: Checking if a key is part of a dictionary

I'm trying to make my own irc bot (for twitch) in Python. 我正在尝试用Python制作自己的irc机器人(用于抽搐)。 I have a dictionary with my commands: 我有一本命令字典:

commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands

Then I have a function to check if the message that was send is indeed a command: 然后,我有一个功能来检查发送的消息是否确实是命令:

import string

def is_valid_command(command):
    return True if command in commands.keys() else False

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong: 因此,当我测试此功能时,它似乎不起作用,并且我不知道自己在做什么错:

message = "!ping"
print(str(is_valid_command(message)))
>>> False

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' 我试图将字典中的“!ping”更改为“!ping”,反之亦然,并删除了该消息,甚至删除了“!” and it always says it's False. 它总是说这是错误的。

Thanks in regards, Laurens 谢谢,劳伦斯

EDIT: 编辑:

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

This result in this: 结果是这样的:

!ping
!random
input !ping
False

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return 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' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding? EDIT3:u'!ping'在解决此问题之前(消息= u'!ping'),但是当我从其他地方读取字符串时,有没有执行此unicoding的函数?

Your is_valid_command function can be simplified to: 您的is_valid_command函数可以简化为:

def is_valid_command(command):
    return command in commands

I just tested your script and it seems to work fine. 我刚刚测试了您的脚本,它似乎运行良好。

Did some simplifications, but basically have the same code as you. 做了一些简化,但是基本上与您具有相同的代码。

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

Which returns True . 返回True If I try command !pong it returns False . 如果我尝试命令!pong则返回False

This pre checking is not needed and unpythonic. 不需要此预检查,并且是非Python的。 Instead of all these ccomplications, just do 代替所有这些并发症,只需

try:
   cmd = commands[message]
   # do whatever with cmd
except KeyError:
   print ('Sorry not a valid command')

EAFP 东亚自由贸易区

Easier to ask for forgiveness than permission. 寻求宽恕比允许容易。 This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. 这种通用的Python编码风格假定有效键或属性的存在,并且在假定被证明为假的情况下捕获异常。 This clean and fast style is characterized by the presence of many try and except statements. 这种干净快捷的样式的特点是存在许多try和except语句。 The technique contrasts with the LBYL style common to many other languages such as C. 该技术与许多其他语言(例如C)通用的LBYL风格形成对比。

Why are you not returning just: 您为什么不只返回:

return command in commands.keys()

That should be True/False already! 那应该是对/错了! hope this clarify! 希望这个澄清!

As mentioned above to create a unicode string out of your messages just: 如上所述,仅从您的消息中创建unicode字符串:

u'%s' % message

I am using python2.7 and your code returns True for me. 我正在使用python2.7,您的代码为我返回True。

Instead of writing function, you can directly use : 除了编写函数,您可以直接使用:

message = "!ping" print(commands.has_key(message))

Yes, there is a function to convert a string to unicode. 是的,有一个函数可以将字符串转换为unicode。 Use unicode function eg unicode('my_string') . 使用unicode函数,例如unicode('my_string')

For example if your message from irc is stored in a variable message_from_irc then you can convert it as unicode(message_from_irc) . 例如,如果来自irc的消息存储在变量message_from_irc则可以将其转换为unicode(message_from_irc)

I suggest you switch keyboard language to English when coding, in order to avoid this types of unexpected behaviors of code. 我建议您在编码时将键盘语言切换为英语,以避免此类意外的代码行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM