Python Dictionary Check if Key Exists

Question:

@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] + "nn**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

Asked By: Dan A

||

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")
Answered By: Raida

Let’s note up front that in python a ‘dictionary’ is a data structure. 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. 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.

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

Answered By: kerasbaz
embed = discord.Embed(description="**Noun:** " + Define["Noun"][0] + "nn**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="nn".join(description),
                          color=0x00ff00)
else:
    # DO SOMETHING ELSE IF IT WAS NOT NOUN OR VERB
Answered By: Shaker al-Salaam