parse a string of parameters and values

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Dec 13 04:27:49 CET 2009


On Sat, 12 Dec 2009 16:16:32 -0800, bsneddon wrote:

> I have a problem that I can come up with a brute force solution to solve
> but it occurred to me that there may be an
>  "one-- and preferably only one --obvious way to do it".

I'm not sure that "brute force" is the right description here. Generally, 
"brute force" is used for situations where you check every single 
possible value rather than calculate the answer directly. One classical 
example is guessing the password that goes with an account. The brute 
force attack is to guess every imaginable password -- eventually you'll 
find the matching one. A non-brute force attack is to say "I know the 
password is a recent date", which reduces the space of possible passwords 
from many trillions to mere millions.

So I'm not sure that brute force is an appropriate description for this 
problem. One way or another you have to read every line in the file. 
Whether you read them or you farm the job out to some pre-existing 
library function, they still have to be read.


> I am going to read a text file that is an export from a control system.
> It has lines with information like
> 
> base=1 name="first one" color=blue
> 
> I would like to put this info into a dictionary for processing. 

Have you looked at the ConfigParser module?

Assuming that ConfigParser isn't suitable, you can do this if each 
key=value pair is on its own line:


d = {}
for line in open(filename, 'r'):
    if not line.strip():
        # skip blank lines
        continue
    key, value = line.split('=', 1)
    d[key.strip()] = value.strip()


If you have multiple keys per line, you need a more sophisticated way of 
splitting them. Something like this should work:

d = {}
for line in open(filename, 'r'):
    if not line.strip():
        continue
    terms = line.split('=')
    keys = terms[0::2]  # every second item starting from the first
    values = terms[1::2]  # every second item starting from the second
    for key, value in zip(keys, values):
        d[key.strip()] = value.strip()




-- 
Steven



More information about the Python-list mailing list