[Tutor] Pouring a list into a dictionary
Alexandre Ratti
alex at gabuzomeu.net
Fri Sep 5 11:43:14 EDT 2003
Hello Allen,
Allen Schmidt wrote:
> I have a file that I parse out to lists.
> The first line contains the column headers.
> The rest of the lines contain the rows of data elements.
How are the column separated? Tabs, commas?
> I need to loop through the each row, grab each column name from the first
> line and would like to use each one as the key in a dictionary.
You can use a variable (say lineCount) in your input loop to keep track
of the current line number. If lineCount == 1, split the 1st line into
chunks. If lineCount > 1, use the chunks as dictionary keys.
Or use the "csv" module, as suggested. This class could be useful:
class DictReader: Create an object which operates like a regular reader
but maps the information read into a dict whose keys are given by the
fieldnames parameter.
http://www.python.org/doc/current/lib/node545.html
> Make sense?? Kinda hard to explain.
If the answers you got do not solve the problem, can you post a sample
of your input file?
Cheers.
Alexandre
More information about the Tutor
mailing list