[Tutor] How do I go from a textFile.txt to a list [] AND from a textFile.txt to a dictionary of dictionaries?

Walter Prins wprins at gmail.com
Mon Jul 23 01:49:12 CEST 2012


Hi Greg,

Try this (next time try solving yourself first and post what you've
done and specific problems you're having trouble with.):

import csv

# read data using csv reader...
fileobj = open('text_data.txt')
csvreader = csv.reader(fileobj, delimiter=';')
csvreader.next() # skip header

# store lines indexed by line id in dict called polylines
# lines themselves are represented by lists.
polylines = {}

# store polygons made up of lines in dict called polygons
polygons = {}

# loop through point data from csvreader and unpack into
# dicts/lists
for line in csvreader:
    #unpack lineid and polyid
    lineid = line[3]
    polyid = line[4]

    # get the point data as list by slicing
    # first entry in list is point id.
    # maybe make points into a dict as well?
    point = line[0:3]

    # store the point in the correct line list:
    # first create an empty list if needed then append
    polylines[lineid] = polylines.get(lineid, [])
    polylines[lineid].append(point)

    # store the line in the correct polygon dict:
    # first create empty dict if needed then add
    # if the line not already part of the polygon.
    polygons[polyid] = polygons.get(polyid, {})
    if not lineid in polygons[polyid]:
        polygons[polyid][lineid] = polylines[lineid]

# check the results with some pretty printing:
import pprint
pp = pprint.PrettyPrinter(indent=4)

print "lines read from csv file:"
pp.pprint(polylines)

print "polygons read from csv file:"
pp.pprint(polygons)

Walter


More information about the Tutor mailing list