On Aug 17, 7:38 am, TYR <[EMAIL PROTECTED]> wrote: > I'd like to do something like this; iterate through a file which > consists of data stored in dictionary format, one dict on each line, > and read each line into a new dict using one of the values in the dict > as its name... > > for example: > > stuff = open('data.txt') > for eachLine in stuff: > name{} > name = eachLine > ....and then do something clever to extract the value of the key > (name) from the line and use it as the dictionary's name. > > A line from data.txt would look like this: {'name' : Bob, 'species' : > Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of > them by name, and merge the values in that dictionary into a string > pulled from another source.
I'm not sure I follow exactly what you want to do, but you can always use eval for each line in that file. But, if the line you provided for testing is one that actually comes from the file, you'll have to patch it before you eval the line. I think this regexp will work. Be careful though, it assumes that all values are whole words, that is they don't have spaces in them. # This is far from ideal, but you get what you pay for :). re.sub(r':\s*(\w+)(,|})', r"': '\1'\2", line) Anyway, after you've cleaned up your input line this ought to work: d = eval(line) Also, if you're building the input file from within a python program, maybe you should consider the pickle module. That ought to give you a good start... jw -- http://mail.python.org/mailman/listinfo/python-list