[英]How to use key/value pairs in a Python dictionary
I wrote a simple code to read a text file. 我编写了一个简单的代码来读取文本文件。 Here's a snippet: 这是一个片段:
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
This last print statement creates the runtime error: 最后一条打印语句会导致运行时错误:
print header['Mode']
KeyError: 'Mode'
The first print statement print header[keyVal[0]]
works fine but the second fails!!! 第一个打印语句print header[keyVal[0]]
正常,但是第二个失败!!! keyVal[0]
IS the string literal 'Mode'
keyVal[0]
是字符串文字'Mode'
Why does using the string 'Mode'
directly fail? 为什么使用字符串'Mode'
直接失败?
split()
with no arguments will split on all consecutive whitespace, so 没有参数的split()
将在所有连续的空格上分割,因此
'foo bar'.split()
is ['foo', 'bar']
. 是['foo', 'bar']
。
But if you give it an argument, it no longer removes whitespace for you, so 但是,如果给它一个参数,它将不再为您删除空格,因此
'foo = bar'.split('=')
is ['foo ', ' bar']
. 是['foo ', ' bar']
。
You need to clean up the whitespace yourself. 您需要自己清理空白。 One way to do that is using a list comprehension: 一种方法是使用列表理解:
[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.