Hello all, this is my first post here.
I seem to have a problem dealing with data, csvs and dictionaries.
Here is a snippet of contents of file 1 (Node,x,y,z):
1,19.0,18.2,22.4
2,8.4,9.4,10.2
4,22.2,2.5,3.1
7,3.2,6.1,4.3
10,3.1,4.2,33.7
11,3.7,23.8,23.4
Here is a snippet contents of file 2 (Node,x,y,z):
1,4.2,7.3,9.5
2,4.1,8.4,9.2
4,2.3,4.6,3.2
11,2.5,2.7,32.6
File 1 in reality has over 10000 lines of data and file 2 as over 2000 lines of data.
Here is my code so far:
import sys
import csv
#Place file1 into a dictionary
f1 = csv.reader(open('file1.csv','rb'))
f1_dict_data = {}
for node1, x1, y1, z1 in f1:
f1_dict_data[node1] = x1,y1,z1
print "Length : %d" % len (f1_dict_data)
#Place file2 into a dictionary
f2 = csv.reader(open('file2.csv', 'rb'))
f2_dict_data = {}
for node2, x2, y2, z2 in f2:
f2_dict_data[node2] = x2,y2,z2
print "Length : %d" % len (f2_dict_data)
# write compared dictionaries to file3
NewCoWriter = csv.writer(open('file3.csv', 'wb', buffering=0))
#Comparing the dictionaries
for key in f1_dict_data:
if key in f2_dict_data:
f1_dict_data[key] = f2_dict_data[key]
a1 = key, f2_dict_data[key]
NewCoWriter.writerow(a1)
else:
a2 = key, f1_dict_data[key]
NewCoWriter.writerow(a2)
This is the results produced by the code so far:
11,"('2.5', '2.7', '32.6')"
10,"('3.1', '4.2', '33.7')"
1,"('4.2', '7.3', '9.5')"
2,"('4.1', '8.4', '9.2')"
4,"('2.3', '4.6', '3.2')"
7,"('3.2', '6.1', '4.3')"
Outcome
Basically this is the results I am after except the following problems:
Problems
1) I can't seem to find a solution for writing the data into a .csv format where all keys and values are separated by a delimiter, e.g. 11,2.5,2.7,32.6 ? Perhaps it would be a better idea to write it out into a formatted .txt file instead? The reason I have used dictionaries is as suggested is because I can then compare two files.
2) I will to sort the data produced in file 3 by the "Node" in ascending order, I have tried ways of doing so without any success.?
3) For some reason when I run this code on the 1000+ lines .csv files all of the dictionary values seem to get jumbled up?
I would really appreciate input from the members. Thanks.