Python Dictionary Check if Key Exists

12,035

Solution 1

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

Solution 2

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")
Share:
12,035

Related videos on Youtube

Dan A
Author by

Dan A

Updated on June 04, 2022

Comments

  • Dan A
    Dan A almost 2 years
    @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

    • Prune
      Prune over 3 years
      if value in my_dict. If you'r enew to dictionaries, then your first recourse is to repeat a tutorial on dicts.
  • Dan A
    Dan A over 3 years
    yes this would work but what would I do if a word has both Verb and Noun, the code would not work
  • Moritz Schmid
    Moritz Schmid over 3 years
    Do a if noun or verb in dict.keys() or if it needs both do if noun and verb in dict.keys()