2014-04-02 14 views
0

我寫了一個簡單的代碼來讀取文本文件。這裏有一個片段:如何在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'直接失敗?

+0

你用'打印header' ....很多時候,一個簡單的打印可幫助您調試的問題得到什麼......你所描述是不正確的...你的字典看起來並不像你想的那樣(也許是它的「模式」或「模式」),你也可以'打印keyVal [0] ==「模式」' –

+1

'{'Mode', '5'}'是Python> = 2.7中的'set',在較老的Pythons中是語法錯誤。你的意思是'{'Mode':5}'? – kojiro

+0

當我要求打印標題時,{'Mode':'5'} – MikRin

回答

1
keyVal = map(str.strip,line.split('=')) #this will remove extra whitespace 

你有空白問題...

+0

是的!就是這樣。非常感謝! – MikRin

2

split()不帶參數會分裂的所有連續空白,所以

'foo bar'.split() 

['foo', 'bar']

但是,如果你給它一個參數,它不再刪除空格給你,所以

'foo = bar'.split('=') 

['foo ', ' bar']

你需要清理自己的空白。要做到這一點的方法之一是使用列表理解:

[s.strip() for s in orig_string.split('=')] 
+0

更深入比我的答案+1 –

+0

是的,這也適用。 Joran's更緊湊!謝謝! – MikRin