Flat file to associative array.

François Pinard pinard at iro.umontreal.ca
Tue Jul 22 04:27:11 CEST 2003

[Delaney, Timothy C (Timothy)]

> > From: Alex [mailto:bogus at antispam.com]
> > 
> > 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

> Have you tried any of the CSV/DSV (delimiter-separated libraries). They
> may be overkill, but you may also be able to get a 1 or 2 line solution
> out of them.

Python does not directly have multi-dimensional arrays deep down, but by
using a tuple as index, we get the feeling and effect of a multi-dimensional

Going without such libraries makes a longer solution, 4 lines maybe :-)
Here is an untried proposal.

dictionary = {}
for line in file('FLAT-FILE-NAME'):
    fields = line.split('|')
    dictionary[tuple(fields[:-1])] = fields[-1].rstrip()

François Pinard   http://www.iro.umontreal.ca/~pinard

More information about the Python-list mailing list