Flat file to associative array.

Alex bogus at antispam.com
Mon Jul 21 01:02:49 EDT 2003


Hello,

What would be the best way to convert a flat file of products into
a multi-dimensional array? The flat file looks like this:

Beer|Molson|Dry|4.50
Beer|Molson|Export|4.50
Shot|Scotch|Macallan18|18.50
Shot|Regular|Jameson|3.00

I've managed to read the file properly and get the individual lines
into a list, but I've got to turn this list into something that can
be stored in memory like a dictionary / associative array so I can
properly display the data.

Here's the code I have so far:

[Code]
#! /usr/bin/python

import string

file = open("definitions", "r")
    
while 1:
    line = file.readline()
    if not line:
        break
    else:
        data = string.split(line, '|')
        item = dict([('product', data[0])])
        print "You want a " + item['product'] +
         ". What kind?  " + data[1] + " for $" +
        data[3] + " ... right?"

file.close()
[/Code]

Thanks in advance,

Alex





More information about the Python-list mailing list