Parsing text file and store these values in python dictionary
I 开发者_运维问答have text file as follows
ID Value 1 Value 2
1 0.8 0.08
2 0.10 0.11
3 11 12
Now the issue is i have to store these values in python dictionary and write to a file..
Can anybody help me how to do this using python
Thanks N
Reading the file into a dict is fairly easy:
# use with statement to open the file
with open(file_name) as f:
# skip first two lines (containing header) and split on whitespace
# this creates a nested list like: [[val1, i1, i2], [val2, i1, i2]]
lines = [x.split() for x in f.readlines()[2:]
# use the list to create the dict, using first item as key, last as values
d = dict((x[0], x[1:]) for x in lines)
This gives you a dict like:
{'1': ['0.8', '0.08'], '2': ['0.10', '0.11'], '3': ['11', '12']}
What format do you want to use to write the dict back out? If you want to write it back out into roughly the same format (I'm assuming it was originally space delimited csv):
import csv
writer = csv.writer(open(out_filename, 'w'), delimiter=' ')
# write header
writer.writerow(['ID', 'Value 1', 'Value 2'])
# write each row
for k,v in d.items():
writer.writerow([k] + v)
精彩评论