mercredi 28 octobre 2015

Parse a file into a dictionary of arrays

I have a csv file with rows of device data like the following:

#file.csv
devA,x1,y1
devB,x1,y1
devA,x2,y2
devC,x1,y1
devC,x2,y2
devA,x3,y3

I want to make a dictionary that makes arrays of the data points, with the device names for keys:

{
    'devA':[
            [x1,y1],[x2,y2],[x3,y3]
         ],
    'devB':[
            [x1,y1]
         ],
    'devC':[
            [x1,y1],[x2,y2]
         ]
}

I've tried the following:

#!/usr/bin/python
#dict.py
import csv,datetime

with open('file.dat', 'rb') as csvfile:
    dataReader=csv.reader(csvfile)
    book={row[0]:[row[1],row[2]] for row in dataReader}
print book

but this outputs

$ ./dict.py 
{'devC': ['x6', 'y6'], 'devB': ['x2', 'y2'], 'devA': ['x7', 'y7']}

I think I see the problem is my book= line is replacing the contents of each key instead of appending. How can I go about getting the desired result in a "Python" way?

Aucun commentaire:

Enregistrer un commentaire