简体   繁体   English

字典只打印并保存最后一项

[英]Dictionary only print and saves the last item

I have a problem, when I try to print all the rows of the csv file, the dictionary only saves and prints the last row.我有一个问题,当我尝试打印 csv 文件的所有行时,字典只保存并打印最后一行。 I have tried to figure out what I was doing wrong and I count find an answer.我试图找出我做错了什么,我想找到答案。

import csv

data = open(r"C:\Desktop\file.csv")
dataReader = csv.reader(data, delimiter = ";")
count = 0
for row in dataReader:
    bookList= dict()
    bookList[row[0]]= row[1]
    print(row)
for k,v in bookList.items():
        print(k,v)

The problem happens because you create a new dictionary instance for each iteration of the loop.出现问题是因为您为循环的每次迭代创建了一个新的字典实例。 Create it once at the beginning, before the loop:在开始时创建一次,在循环之前:

import csv
data = open(r"C:\Desktop\file.csv")
dataReader = csv.reader(data, delimiter = ";")
count = 0
bookList = dict()
for row in dataReader:
    bookList[row[0]]= row[1]
    print(row)
for k,v in bookList.items():
        print(k,v)

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

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