英文:
Appending a dictionary to a dictionary
问题
我以字典形式打开了CSV文件,并尝试逐行将其附加到现有的字典中。但似乎并没有附加成功。相反,在循环中,现有的字典只保留了当前行。那么,我做错了什么?
buffer = {}
with open("small.csv", "r") as input:
reader = csv.DictReader(input)
for row in reader:
buffer |= row
print(buffer)
Buffer字典应该存储读取器中的所有行,但实际上它只包含了当前行。我尝试使用buffer.update(row)
,但得到了相同的结果。
英文:
I opened csv file as dictionary and try to append it to existing dictionary row by row. But it seems like it's not appending. rather, the existing dictionary only holding current row in a loop. So, what am I doing wrong?
buffer = {}
with open("small.csv", "r") as input:
reader = csv.DictReader(input)
for row in reader:
buffer |= row
print(buffer)
Buffer dictionary is supposed to store all rows in reader, but it's only holding current row. I tried to use buffer.update(row)
but found same result.
答案1
得分: 1
你不能向字典中添加 "rows"。你需要使用一个 list
,即:
buffer = []
然后
...
for row in reader:
buffer.append(row)
...
最终,你的 buffer
将是一个包含多个字典的列表,其中每个字典代表一个单独的行。
英文:
You can't add "rows" to a dictionary. What you need is a list
, i.e:
buffer = []
then
...
for row in reader:
buffer.append(row)
...
In the end your buffer
will be a list of dicts, where each dict is a separate row.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论