将一个字典追加到另一个字典中

huangapple go评论53阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月24日 08:15:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定