簡體   English   中英

如果值匹配我在python中的字典,我該如何匹配

[英]how do i match if value match my dictionary in python

我是python的超級新手,所以我什至對基礎函數的基礎一無所知,所以誰能告訴我如何將值與我的字典匹配以及我在哪里做錯了

#dictionary
id = {"2":"30", "3":"40"}

#json display from web
messages: {"id":2,"class":0,"type":1,"member":"N"}

if messages['id'] == id:  # << this part i think i'm doing it wrong too because it prints error`
    print ('the new id value from dictionary')  # << what do i put in here`
else:
    print ('error')

在 id 中使用if str(messages['id']) in id而不是if messages['id'] == id

要檢查值是否是 dict 中的鍵,您可以這樣做:

if messages['id'] in id:

但在您的情況下它不會立即起作用。 json 數據中的值是整數,因此您需要將它們轉換為匹配字典。 你最終會得到這個

if str(messages['id']) in id:

完整代碼:

id = {"2": "30", "3": "40"}
messages = {"id":2,"class":0,"type":1,"member":"N"}
if str(messages['id']) in id:
    print(id[str(messages['id'])])
else:
    id[str(messages['id'])] = '50'

發生錯誤是因為您需要使用=來分配變量:

messages = {"id":2,"class":0,"type":1,"member":"N"}

代替

messages: {"id":2,"class":0,"type":1,"member":"N"}

關於您想要實現的目標,您正在嘗試通過使用默認值 ( "error" ) 來訪問字典值,以防密鑰不存在。 您可以為此使用dict.get ,而不是if-else

#dictionary
id_dict = {"2":"30", "3":"40"}

#json display from web
messages = {"id":2,"class":0,"type":1,"member":"N"}
    
print(id_dict.get(messages['id'], "error"))

注意事項:

  • 不要使用id作為變量名,因為它是 Python 內置關鍵字。
  • 如果id_dict有字符串鍵,你還需要使用字符串來訪問它,即messages = {"id":2 ...不會給你值"30" for id_dict = {"2":"30", "3":"40"}

您需要將要檢查的值轉換為字符串才能執行有效比較。 此外,您不應使用 Python 關鍵字作為名稱變量以避免其他問題:

id_dict = {"2":"30", "3":"40"}

#Use = to assign variables, not :
messages = {"id":2,"class":0,"type":1,"member":"N"}

if str(messages['id']) in id_dict:
    print ('the new id value from dictionary') 
else:
    print ('error')

輸出:

the new id value from dictionary

暫無
暫無

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

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