I have a csv that is formated this way, notice there are multiple records at the same time and within that timeframe there are multiple records with the same data4 value:
Time,data1,data2,data3,data4
8/12/2017 8:37:11.719,4435441.97983871,321106.049167927,1260.354,64
8/12/2017 8:37:11.719,4435451.97715054,321346.085476551,1260.354,60
8/12/2017 8:37:11.719,4435461.97446237,321096.047655068,1260.354,64
8/12/2017 8:37:11.719,4435461.97446237,321106.049167927,1260.354,64
8/12/2017 8:37:26.919,4436121.79704301,324496.562027231,1260.354,96
8/12/2017 8:37:26.919,4436121.79704301,324506.563540091,1260.354,96
8/12/2017 8:37:26.919,4436121.79704301,324546.569591528,1260.354,56
8/12/2017 8:37:26.919,4436121.79704301,324646.584720121,1260.354,64
I'm trying to write a function to read this csv into a nested dictionary that uses the Time column and the data4 column to as nested keys. What I have so far is this:
def build_dict(source_file):
new_dict = defaultdict(dict)
headers = ['Time','data1','data2','data3','data4']
with open(source_file, 'rb') as fp:
reader = csv.DictReader(fp, fieldnames=headers, dialect='excel',
skipinitialspace=True)
for rowdict in reader:
if None in rowdict:
del rowdict[None]
Time = rowdict.pop("Time")
data4 = int(rowdict.pop("data4"))
dict[Time][data4] = rowdict
return dict(new_dict)
Which returns:
new_dict = {
'8/12/2017 8:37:11.719' : {
64: {'data3': '1260.354', 'data1': '4435441.97983871', 'data2': '321106.049167927'},
60: {'data3': '1260.354', 'data1': '4435451.97715054', 'data2': '321346.085476551'}
}
}
It's almost doing what I need but it overwrites the previous row data with Time and data4 are the same. I'm thinking I need to store data1, data2 and data3 in a list but not sure how to do it.
This is what I would like my dictionary to look like so that per time period I can group data by data4 values:
new_dict = {
'8/12/2017 8:37:11.719' : {
60 : [
{'data1': '4435451.97715054', 'data2': '321346.085476551', 'data3': '1260.354'}
],
64 : [
{'data1': '4435441.97983871', 'data2': '321106.049167927', 'data3': '1260.354'},
{'data1': '4435461.97446237', 'data2': '321096.047655068', 'data3': '1260.354'},
{'data1': '4435461.97446237', 'data2': '321106.049167927', 'data3': '1260.354'}
]
}
}