簡體   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)

我想檢查NounVerb是否在字典中Define ,因為當一個詞在其定義中只有一個名詞時,它會拋出一個錯誤,因為我試圖用機器人 output 名詞和動詞,看看我得到了什么在。 我是字典新手,非常感謝任何幫助

讓我們提前注意,在 python 中,“字典”是一種數據結構 您正在使用第三方庫來執行字典查找(如詞匯含義)。

需要知道如何判斷 python 字典數據結構是否包含鍵。 把“字典”這個詞的這些用法分開記在心里,否則你很快就會感到困惑。 在大多數 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

您可以使用以下代碼測試密鑰是否存在:

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)

你把它改成

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