我有一本字典(cell0),其鍵如下所示。很明顯,我的字典中有一個名為“46”的鍵。我已經(jīng)確認(rèn)該密鑰中有正確的數(shù)據(jù)。當(dāng)我使用 for 循環(huán)并嘗試迭代字典來執(zhí)行某些任務(wù)時,它顯示“KeyError:46”。誰能幫助理解為什么會發(fā)生這種情況?cell0.keys()我執(zhí)行了以下填充操作以使所有數(shù)組的大小相同。for key in cell0:for i in cell0[i]: x = cell0[i]['I'].shape x = sum(x) y = cell0[i][key].shape y = sum(y) l = (x-y) if x != y: cell0[i][key] = np.pad((cell0[i][key]),[(0,l)],mode='constant', constant_values=0)當(dāng)我使用上面的代碼運行單元時,我收到這樣的錯誤。KeyError Traceback (most recent call last)<ipython-input-9-0955afc863ef> in <module> 1 for key in cell0: 2 ----> 3 for i in cell0[i]: 4 x = cell0[i]['I'].shape 5 x = sum(x)KeyError: 46
1 回答

達(dá)令說
TA貢獻(xiàn)1821條經(jīng)驗 獲得超6個贊
如果 cell0 是字典,則不能對其進行切片 ----> for i in cell0[i]
考慮到 'dict_keys'(cell0.keys()) 對象也是不可下標(biāo)的
您可以使用 cell0.items() 來訪問鍵和值
請注意,最好使用 cell0.get(key) 方法來訪問字典中的值
for key, value in cell0.items(): x = value.get("I").shape() ...# your code
添加回答
舉報
0/150
提交
取消