我定義了兩個字典dict1和dict2. 我希望用戶通過輸入告訴我要訪問哪個字典(當然他必須知道確切的名稱),所以他從這個字典中獲取一個值。以下不起作用,我得到一個類型錯誤“字符串索引必須是整數”:dict1 = {'size': 38.24, 'rate': 465}dict2 = {'size': 32.9, 'rate': 459}name = input('Which dictionary to access?: ')ret = name['size']print ('Size of ' + name + ' is ' + str(ret))
2 回答

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
dict1 = {'size': 38.24, 'rate': 465}
dict2 = {'size': 32.9, 'rate': 459}
name = input('Which dictionary to access?: ')
if name == 'dict1':
ret = dict1['size']
eif name == 'dict2':
ret = dict2['size']
print ('Size of ' + name + ' is ' + str(ret))
或者
input_to_dict_mapping = {'dict1':dict1,'dict2':dict2}
ret = input_to_dict_mapping[name]['size']
或來自 Antwane 的回應。
更新
input_to_dict_mapping = globe()
ret = input_to_dict_mapping[name]['size']
問題是name is a string value。你不能像我們在 Dict 中那樣做索引。
添加回答
舉報
0/150
提交
取消