Python字典检查键是否存在

3
@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)

我想检查词典Define中是否有NounVerb,因为当一个单词只在其定义中有名词时,会抛出错误,因为我试图让机器人输出名词和动词,你能理解我的意思吗?我对词典不太熟悉,希望得到帮助。


3
如果你对字典不熟悉,那么你首先应该重复一下有关字典的教程。if value in my_dict 的意思是:如果某个值在我的字典中。 - Prune
3个回答

14

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

if key_to_test in dict.keys():
   print("The key exists")
else:
   print("The key doesn't exist")

是的,这样做是可行的,但如果一个单词既是动词又是名词,那么代码就无法正常工作。 - Dan A
3
如果需要判断名词或动词是否在字典的键中,可以使用if noun or verb in dict.keys();如果需要同时满足名词和动词在字典的键中,可以使用if noun and verb in dict.keys() - Moritz Schmid
什么?那行不通。 - schuelermine
应该是 if (名词或动词) 在字典中 或者 if (名词和动词) 在字典中。我刚刚测试过,在 Python 3.10 上可以正常工作。 - Raida

1
请注意,在Python中,“字典”是一种数据结构。您正在使用第三方库执行字典查找(如词汇含义)。
您还需要知道如何判断Python字典数据结构是否包含键。请将这些用法中的“字典”分开考虑,否则您很快就会感到困惑。在大多数Python环境中,人们会认为“字典”指的是数据结构,而不是像Webster的词汇字典。
from PyDictionary import PyDictionary

dictionary=PyDictionary()

meanings = dictionary.meaning("test")

if 'Noun' in meanings and 'Verb' in meanings:
    #do everything
elif 'Noun' in meanings:
    #do something
elif 'Verb' in meanings:
    #do something else


0
embed = discord.Embed(description="**Noun:** " + Define["Noun"][0] + "\n\n**Verb:** " + Define["Verb"][0], color=0x00ff00)

你把它改成这样
description = []
if "Noun" in Define:
    description.append("**Noun:** " + Define["Noun"][0])
if "Verb" in Define:
    description.append("**Verb:** " + Define["Verb"][0])

if description:
    embed = discord.Embed(description="\n\n".join(description),
                          color=0x00ff00)
else:
    # DO SOMETHING ELSE IF IT WAS NOT NOUN OR VERB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接