Flat file to associative array.

Antti Kaihola akaihola at ambi-spam-me-not-tone.com
Mon Jul 21 12:40:01 EDT 2003


#!/usr/bin/env python

def line2dict(line, fieldnames, sep='|'):
     """
     Convert a separated text line to a dictionary
     with the given field names as keys
     """
     d = {}
     for fieldname, value in zip(fieldnames, line.split(sep)):
         d[fieldname] = value
     return d

drinkfields = 'drinktype', 'producer', 'brand', 'price'
def drinkline2dict(line):
     """
     Convert a | -separated and linefeed-terminated text line
     to a dictionary
     """
     return line2dict(line.rstrip(), drinkfields, '|')

products = map(drinkline2dict, file('products.txt').readlines())
from pprint import pprint
pprint(products)





More information about the Python-list mailing list