简体   繁体   English

Python 字典检查密钥是否存在

[英]Python Dictionary Check if Key Exists

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

I want to do check if Noun and Verb is in the dictionary Define , because when a word only has lets say a Noun in its definition then it throws an error because I am trying to bot output the Noun and Verb, see what I am getting at.我想检查NounVerb是否在字典中Define ,因为当一个词在其定义中只有一个名词时,它会抛出一个错误,因为我试图用机器人 output 名词和动词,看看我得到了什么在。 I am new to dictionaries and any help is much appreciated我是字典新手,非常感谢任何帮助

Let's note up front that in python a 'dictionary' is a data structure .让我们提前注意,在 python 中,“字典”是一种数据结构 You're using a third-party library to perform dictionary lookups (as in lexical meanings).您正在使用第三方库来执行字典查找(如词汇含义)。

You also need to know how to tell if a python dictionary data structure contains a key.需要知道如何判断 python 字典数据结构是否包含键。 Keep these uses of the word 'dictionary' separate in your mind or you will rapidly get confused.把“字典”这个词的这些用法分开记在心里,否则你很快就会感到困惑。 In most python contexts people will assume 'dictionary' means the data structure, not a lexical dictionary like Webster's.在大多数 python 上下文中,人们会假设“字典”是指数据结构,而不是像韦伯斯特那样的词汇字典。

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

You can test if key exists with the following code:您可以使用以下代码测试密钥是否存在:

if key_to_test in dict.keys():
   print("The key exists")
else:
   print("The key doesn't exist")
embed = discord.Embed(description="**Noun:** " + Define["Noun"][0] + "\n\n**Verb:** " + Define["Verb"][0], color=0x00ff00)

You change it to你把它改成

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

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

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