我是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')
uj5u.com熱心網友回復:
使用if str(messages['id']) in id代替if messages['id'] == id
uj5u.com熱心網友回復:
要檢查值是否是 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'
uj5u.com熱心網友回復:
發生錯誤是因為您需要使用 an=來分配變數:
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"提供id_dict = {"2":"30", "3":"40"}.
uj5u.com熱心網友回復:
您需要將要檢查的值轉換為字串才能執行有效比較。此外,您不應使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/497559.html
上一篇:使用預定義的標頭將串列字典轉換為pandas.DataFrame
下一篇:字典串列的向量化方法
