如何在字典下添加列表?

时间:2014-12-15 10:52:58

标签: 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

我正在尝试创建一个数据结构,我可以将进程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

我的问题是使用这个我没有得到键下的行列表,但只有我放在那里的最后一个值。如果我知道这一点,这是合乎逻辑的。如何添加(列表)行列表,这是我的意图?

1 个答案:

答案 0 :(得分:8)

如果密钥尚未存在,您可以使用dict.setdefault()创建一个空列表,并将您的行追加到列表中(新创建或不创建):

threads = {}
for row in csv_f:
    # Populate already the list of processes
    processes.append(row[2])
    threads.setdefault(row[2], []).append(row)