我試圖能夠根據用戶定義的變數回傳特定字典的預算編號。我沒有任何運氣自己解決這個問題,非常感謝任何幫助。
owners = ['rob','andre']
team_balance = {}
for name in owners:
team_balance[name.capitalize()] ={'budget':200}
x='Rob' # x will be user defined using input()
print(team_balance[{x}]['budget'])
嘗試上述結果會導致以下錯誤:
TypeError: unhashable type: 'set'
uj5u.com熱心網友回復:
owners = ['rob','andre']
team_balance = {}
for name in owners:
team_balance[name.capitalize()] ={'budget':200}
x=input() # user will enter this value
使用 try except 處理例外
try:
print(team_balance[x.capitalize()]['budget'])
except:
print("Entered value not in owners list ")
uj5u.com熱心網友回復:
你只需要像這樣省略花括號:
print(team_balance[x]['budget'])
如果你添加它們,結果是一個集合,你可以像這樣檢查:
isinstance({x}, set)
集合不能用作字典鍵,因為它是不可散列的(這幾乎意味著它可以更改)。
uj5u.com熱心網友回復:
問題來自最后一行的“{}”。
當你定義你的字典時,你使用字串作為鍵。因此,當您從字典中呼叫一個值時,您必須使用字串。
x='Rob'還分配了一個字串 in x,所以它是不是很好。我們可以使用該函式type來檢查物件的類:
>>> type(x)
<class 'str'>
最后一行的問題是{x}將您的字串轉換為一組字串。集合就像一個串列,但無序、不可更改且只有唯一值。
>>> type({x})
<class 'set'>
因此,由于您使用的物件型別與用于設定值的物件型別不同,因此它無法作業。
你得到的錯誤資訊TypeError: unhashable type: 'set'是因為一個集合物件是不可使用的,所以它不能用作字典鍵(這里解釋了為什么)。但是,即使一個集合是一個 hasable 物件,你也不會有你想要的值,因為它不等于你用來定義鍵的值。
只需洗掉{}:
owners = ['rob','andre']
team_balance = {}
for name in owners:
team_balance[name.capitalize()] ={'budget':200}
x='Rob' # x will be user defined using input()
print(team_balance[x]['budget'])
>>> 200
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/484429.html
上一篇:在帶有條件的f字串中列印變數
