Python 如何在字典下添加列表?

Python 如何在字典下添加列表?,python,Python,我输入了以下格式的csv文件: #date,time,process(id),thread(id),cpuusage 201412120327,03:27,process1(10),thread1(12),10 201412120327,03:27,process2(11),thread1(13),10 201412120328,03:28,process1(10),thread2(12),10 201412120328,03:28,process2(10),thread2(13),10 我正

我输入了以下格式的csv文件:

#date,time,process(id),thread(id),cpuusage
201412120327,03:27,process1(10),thread1(12),10
201412120327,03:27,process2(11),thread1(13),10
201412120328,03:28,process1(10),thread2(12),10
201412120328,03:28,process2(10),thread2(13),10
我正在尝试创建一个数据结构,在这个结构中,我可以使用进程id作为与之匹配的csv所有条目的has键。请参阅下面的代码

# open the file
f = open (cvs_file)
csv_f = csv.reader(f)

# List of processes, with all the repetitions
processes = []
# Dictionary for the threads
threads = {}
for row in csv_f :
    # Populate already the list of processes
    processes.append(row[2])
    threads[row[2]] = row
我的问题是,使用它,我不会得到键下的行列表,而只会得到最后一个值。如果我仔细想想的话,这是合乎逻辑的。如何添加我想要的(列表)行列表?

如果键还不存在,您可以使用创建空列表,并将您的行附加到列表中(新创建或未创建):


@PadraicCunningham:对于这个用例,
dict.setdefault
只是。。更简单。它就在默认类型上,不需要导入,也不需要解释如何转换回常规字典(或者为什么它不重要)。谢谢,@MartijnPieters它完全满足了我的需要。
threads = {}
for row in csv_f:
    # Populate already the list of processes
    processes.append(row[2])
    threads.setdefault(row[2], []).append(row)