開(kāi)心每一天1111
2021-09-14 13:48:27
我定義了兩個(gè)字典dict1和dict2. 我希望用戶通過(guò)輸入告訴我要訪問(wèn)哪個(gè)字典(當(dāng)然他必須知道確切的名稱),所以他從這個(gè)字典中獲取一個(gè)值。以下不起作用,我得到一個(gè)類型錯(cuò)誤“字符串索引必須是整數(shù)”: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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
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']
或來(lái)自 Antwane 的回應(yīng)。
更新
input_to_dict_mapping = globe()
ret = input_to_dict_mapping[name]['size']
問(wèn)題是name is a string value。你不能像我們?cè)?Dict 中那樣做索引。
添加回答
舉報(bào)
0/150
提交
取消