In the CSV I’m reading from, there are multiple rows for each ID:
JavaScript
x
7
1
ID,timestamp,name,text
2
444,2022-03-01T11:05:00.000Z,Amrita Patel,Hello
3
444,2022-03-01T11:06:00.000Z,Amrita Patel,Nice to meet you
4
555,2022-03-01T12:05:00.000Z,Zach Do,Good afternoon
5
555,2022-03-01T11:06:00.000Z,Zach Do,I like oranges
6
555,2022-03-01T11:07:00.000Z,Zach Do,definitely
7
I need to extract each such that I will have one file per ID, with the timestamp, name, and text in that file. For example, for ID 444, it will have 2 timestamps and 2 different texts in it, along with the name.
I’m able to get the text designated to the proper ID, using this code:
JavaScript
1
12
12
1
from collections import defaultdict
2
3
d = {}
4
l = []
5
list_of_lists = []
6
7
for k in csv_file:
8
l.append([k['ID'],k['text']])
9
list_of_lists.append(l)
10
for key, val in list_of_lists[0]:
11
d.setdefault(key, []).append(val)
12
The problem is that this isn’t enough, I need to add in the other values to the one ID key. If I try:
JavaScript
1
2
1
l.append([k['ID'],[k['text'],k['name']]])
2
I get
JavaScript
1
2
1
ValueError: too many values to unpack
2
Advertisement
Answer
Just use a list for value instead,
JavaScript
1
2
1
{key: [value1, value2], }
2