2016-11-30 67 views
1

我有一个包含此索引:KeyError异常但肯定在字典

IRD\0.jpg [ 4.64939594e-01 6.48846030e-02 2.00261129e-04  0.00000000e+00 0.00000000e+00 ... 7.34290807e-04 6.90233335e-02 2.02463999e-01] 

但这里调用时:

for (k, hist) in index.items(): 
    # compute the distance between the two histograms 
    # using the method and update the results dictionary 
    d = method(index['IRD\0.jpg'], hist) 
    results[k] = d 

谈到了这个错误:

KeyError Traceback (most recent call last) 
<ipython-input-98-b7c782484164> in <module>() 
# compute the distance between the two histograms 
# using the method and update the results dictionary 
d = method(index['IRD\0.jpg'], hist) 
results[k] = d 

我真的不明白为什么? 帮助将高度赞赏,我很抱歉,如果我失去了明显的东西,但我是相当新的:)

+0

是'index'实际上是一个长度为2元组的列表,如你所暗示的? – Anonymous

+1

这并不像蟒蛇可以“困惑”,并没有意识到关键在那里。如果你得到一个关键的错误,那么你做错了什么。打印索引的所有键,在循环中,你会看到 – Anonymous

+0

@jphollowed索引包含键(文件名),值是像素值,我会 – ExJasmine

回答

0

这是因为\是字符串中的转义字符。如果你希望它被解释为字符串中的字符实际,那么你必须要逃避它:

>>> print('x\0') 
x 
>>> print('x\\0') 
x\0 

所以更改index['IRD\0.jpg']index['IRD\\0.jpg']

+1

非常感谢,错误现在消失了! (我的意思是我一直在努力解决这个问题,这很简单,所以谢谢你,谢谢,谢谢!) – ExJasmine