简体   繁体   English

向一个键添加多个值,但 defaultdict 只允许 2

[英]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:在我正在阅读的 CSV 中,每个 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.我需要提取每一个文件,以便每个 ID 有一个文件,其中包含时间戳、名称和文本。 For example, for ID 444, it will have 2 timestamps and 2 different texts in it, along with the name.例如,对于 ID 444,它将包含 2 个时间戳和 2 个不同的文本以及名称。

I'm able to get the text designated to the proper ID, using this code:我可以使用以下代码获取指定给正确 ID 的文本:

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.问题是这还不够,我需要将其他值添加到一个 ID 键中。 If I try:如果我尝试:

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

I get我明白了

ValueError: too many values to unpack

Just use a list for value instead,只需使用列表作为值,

{key: [value1, value2], ...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM