[英]How to use key/value pairs in a Python dictionary
我編寫了一個簡單的代碼來讀取文本文件。 這是一個片段:
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 header[keyVal[0]]
正常,但是第二個失敗!!! keyVal[0]
是字符串文字'Mode'
為什么使用字符串'Mode'
直接失敗?
沒有參數的split()
將在所有連續的空格上分割,因此
'foo bar'.split()
是['foo', 'bar']
。
但是,如果給它一個參數,它將不再為您刪除空格,因此
'foo = bar'.split('=')
是['foo ', ' bar']
。
您需要自己清理空白。 一種方法是使用列表理解:
[s.strip() for s in orig_string.split('=')]
keyVal = map(str.strip,line.split('=')) #this will remove extra whitespace
你有空格問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.