MikRin
MikRin

Reputation: 3

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!!! keyVal[0] IS the string literal 'Mode'

Why does using the string 'Mode' directly fail?

Upvotes: 0

Views: 110

Answers (2)

kojiro
kojiro

Reputation: 77059

split() with no arguments will split on all consecutive whitespace, so

'foo    bar'.split()

is ['foo', 'bar'].

But if you give it an argument, it no longer removes whitespace for you, so

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

is ['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('=')]

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113940

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

you have whitespace problems ...

Upvotes: 1

Related Questions