Skip to content
Advertisement

add multiple values to one key, but defaultdict only allows 2

In the CSV I’m reading from, there are multiple rows for each ID:

ID,timestamp,name,text
444,2022-03-01T11:05:00.000Z,Amrita Patel,Hello
444,2022-03-01T11:06:00.000Z,Amrita Patel,Nice to meet you
555,2022-03-01T12:05:00.000Z,Zach Do,Good afternoon
555,2022-03-01T11:06:00.000Z,Zach Do,I like oranges
555,2022-03-01T11:07:00.000Z,Zach Do,definitely

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:

from collections import defaultdict

d = {}
l = []
list_of_lists = []

for k in csv_file:
    l.append([k['ID'],k['text']])
    list_of_lists.append(l) 
for key, val in list_of_lists[0]:
    d.setdefault(key, []).append(val)

The problem is that this isn’t enough, I need to add in the other values to the one ID key. If I try:

l.append([k['ID'],[k['text'],k['name']]])

I get

ValueError: too many values to unpack

Advertisement

Answer

Just use a list for value instead,

{key: [value1, value2], ...}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement