csv Python:为什么我的代码在打印字典的第一行后停止?

vh0rcniy  于 2023-09-28  发布在  Python
关注(0)|答案(1)|浏览(101)

我想把一个文件的内容输入到一个字典中。我的代码按预期打印第一行,但之后无法打印第二行
我尝试使用DictReader而不是Reader模块,下面是我的代码:

import csv
def read_portfolio(filename):
    portfolio = {}
    with open (filename) as f:
        rows = csv.reader(f)
        headers= next(f)
        for row in rows:
            #portfolio[row['name']] = {'shares': row['shares'], 'price': row['price']}
            portfolio=[{'name':row[0],'shares':row[1],"price":row[1]}]
    return portfolio

myportfolio = read_portfolio('portfolio.csv')
print(myportfolio)
2vuwiymt

2vuwiymt1#

你应该给字典的键赋值,而不是重新赋值变量。变化

portfolio=[{'name':row[0],'shares':row[1],"price":row[1]}]

portfolio[row[0]]={'shares':row[1],"price":row[1]}

相关问题