Python字典检查key是否存在

Dan*_*n A 3 python dictionary python-3.x discord.py

@commands.command(aliases=['lookup'])
    async def define(self, message, *, arg):
        dictionary=PyDictionary()
        Define = dictionary.meaning(arg)
        length = len(arg.split())
        if length == 1:
            embed = discord.Embed(description="**Noun:** " + Define["Noun"][0] + "\n\n**Verb:** " + Define["Verb"][0], color=0x00ff00)
            embed.set_author(name = ('Defenition of the word: ' + arg),
            icon_url=message.author.avatar_url)
            await message.send(embed=embed)
        else:
            CommandError = discord.Embed(description= "A Term must be only a single word" , color=0xfc0328)
            await message.channel.send(embed=CommandError)
Run Code Online (Sandbox Code Playgroud)

我想检查 和 是否NounVerb字典中Define,因为当一个单词在其定义中只包含一个名词时,它会抛出一个错误,因为我试图通过机器人输出名词和动词,看看我得到了什么。我是字典新手,非常感谢任何帮助

Rai*_*ida 14

您可以使用以下代码测试密钥是否存在:

if key_to_test in dict.keys():
   print("The key exists")
else:
   print("The key doesn't exist")
Run Code Online (Sandbox Code Playgroud)

  • 执行 `if noun or verb in dict.keys()` 或者如果需要两者都执行 `if noun and verb in dict.keys()` (3认同)