簡體   English   中英

python字典檢查與關鍵

[英]python dictionary checking with key

我想檢查我的密鑰是否等於輸入:

topics = c.classify("what about ")
a = topics.keys() 
if a == "resources": 
    print("yes")

但是a存儲為dict_keys(['resource“])我希望a只是“ resources”,有人可以幫我嗎?

您應該首先將鍵轉換為常規的python列表,然后在其中進行迭代(您可能無需轉換就可以執行此操作,但我認為查找起來更簡單)。

topics = c.classify("what about ")
a = list(topics.keys())
for key in a:
    if key == "resources": 
        print("yes")

不要忘記一個字典可以有多個值。 正如@ rob-bricheno所說,您可以使用in運算符來簡化它。 此運算符將遍歷list ,如果指定的元素在list ,則返回True ,否則返回False值。 因此,您可以使用以下簡化代碼來做到這一點:

topics = c.classify("what about ")
a = list(topics.keys())
if "resources" in a:
    print("yes")

resources是在a列表中,如果條件為True ,所以print將調用。 如果不在a ,將跳過print

您可以in中使用。 將其與字典一起使用時,它將檢查您指定的值是否是字典中的鍵。

topics = c.classify("what about ")
if "resources" in topics:
    print("yes")

這是最快,最標准的方法。 在此處閱讀更多Python字典鍵。 復雜度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM