Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary Check if Key Exists [duplicate]

@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. I am new to dictionaries and any help is much appreciated

like image 341
Dan A Avatar asked Sep 08 '25 11:09

Dan A


1 Answers

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")
like image 107
Raida Avatar answered Sep 10 '25 06:09

Raida