Reading csv file in Python and create a dictionary -
i trying read csv file in python 27 create dictionary. csv file looks like-
si1440269,si1320943,si1321085 si1440270,si1320943,si1321085,si1320739 si1440271,si1320943
si1440273,si1321058,si1320943,si1320943
number of entries in each row not fixed. first column entries should keys. code -
import csv reader = csv.reader(open('test.csv')) result = {} column in reader: key = column[0] if key in result: pass result[key] = column[1:] print result
output:
{'si1440273': ['si1321058', 'si1320943', 'si1320943'], '': ['', '', ''], 'si1440271': ['si1320943', '', ''], 'si1440270': ['si1320943', 'si1321085', 'si1320739'], 'si1440269': ['si1320943', 'si1321085', '']}
how can rid of null values in output? also, how can have key values in output in same order in csv file?
edit: want single row per 'key'
try this
import csv reader = csv.reader(open('test.csv')) result = {row[0]:row[1:] row in reader if row , row[0]} print result
if want further more eliminate null in values bellow
import csv reader = csv.reader(open('test.csv')) result = {row[0]:[i in row[1:] if i] row in reader if row , row[0]} print result
to preserve order of entry
from collections import ordereddict result = ordereddict() row in reader: if row , row[0]: result[row[0]]=[i in row[1:] if i] # print result key in result: print key,":" ,result[key]
Comments
Post a Comment