我有以下格式的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
我的问题是,使用此方法我不会在键下获得行的列表,而只会得到我放在那里的最后一个值。如果我认为这是合乎逻辑的。我该如何添加(列表)行列表?
dict.setdefault()
如果密钥尚不存在,您可以用来创建一个空列表,然后将行附加到列表中(是否新创建):
threads = {}
for row in csv_f:
# Populate already the list of processes
processes.append(row[2])
threads.setdefault(row[2], []).append(row)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句