我寫了一個簡單的代碼來讀取文本文件。這裏有一個片段:如何在Python字典中使用鍵/值對
linestring = open(wFile, 'r').read()
# Split on line Feeds
lines = linestring.split('\n')
num = len(lines)
print num
numHeaders = 18
proc = lines[0]
header = {}
for line in lines[1:18]:
keyVal = line.split('=')
header[keyVal[0]] = keyVal[1]
# note that the first member is {'Mode', '5'}
print header[keyVal[0]] # this prints the number '5' correctly
print header['Mode'] # this fails
這最後的打印語句創建運行時錯誤:
print header['Mode']
KeyError: 'Mode'
第一個print語句print header[keyVal[0]]
工作正常,但第二次失敗! keyVal[0]
是字符串文字'Mode'
爲什麼使用字符串'Mode'
直接失敗?
你用'打印header' ....很多時候,一個簡單的打印可幫助您調試的問題得到什麼......你所描述是不正確的...你的字典看起來並不像你想的那樣(也許是它的「模式」或「模式」),你也可以'打印keyVal [0] ==「模式」' –
'{'Mode', '5'}'是Python> = 2.7中的'set',在較老的Pythons中是語法錯誤。你的意思是'{'Mode':5}'? – kojiro
當我要求打印標題時,{'Mode':'5'} – MikRin