I am using a dictionary to group data from a CSV file, so for instance fist and second columns are the dict key and value will be a list of tuples with column 3,4.
my code snippet is:
import csv
import collections
csvDicData_ = dict()
fh = open('myfile.csv', 'rt')
reader = csv.reader(fh, delimiter=';', skipinitialspace=True)
for indx, row in enumerate(reader):
if row:
#-- put in a dictionary form: #csvDicData_[(row[0],row[1])] = (row[2],row[3])
key = (row[0],row[1])
value = (row[2],row[3])
#-- I'd like to use the row below (commented) insted of the next two, I expect the same result...
#csvDicData_.setdefault(key,[value]).append(value)
if (not key in csvDicData_): csvDicData_[key] = [value]
else: csvDicData_[key].append(value)
The code above produces the correct result, altough I tried to use csvDicData_.setdefault(key,[value]).append(value)
and for some reason that I do not understand, the len(csvDicData_[('field1x','field2x')] ))
has always one more item (with value (0,0) that expected.
Why this behaviour (it is like the first line in the CSV file for each key automatically adds the tuple (0,0) to the dictionary/key.