我基本上是想用自己的命名键将csv文件转换成字典,但由于某种原因,我遇到了语法错误。我正在使用最新的Python btw。csv文件如下所示:
1|apple|0.50|60
2|orange|0.4|55
3|mango|0.6|33
我想为每种水果创建一个这种形式的词典:
dictionary={
'1':{'fruit':'apple',
'price':0.5,
'stock':60},
'2':{...},
'3':{...},
}
这是我的尝试:
with open('fruit.csv', mode="rt", encoding="utf8") as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
product={row[0]:{'fruit'=row[1],'price'=row[2],'stock'=row[3]}}
print(product)
但这似乎并不奏效:(我是Python的新手,我仍在努力学习。谢谢大家!
您的语法确实错误。
你可能正在寻找
products = {}
with open("fruit.csv", mode="rt", encoding="utf8") as f:
reader = csv.reader(f, delimiter="|")
for row in reader:
products[row[0]] = {"fruit": row[1], "price": row[2], "stock": row[3]}
print(products)
在处理CSV时,我们使用'='而不是':'。你的语法是错误的。试试这个。
import csv
di = {}
with open('fruit.csv', mode="rt", encoding="utf8") as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
di[row[0]] = {'fruit':row[1],'price':row[2],'stock':row[3]}
print(di)
你应该喜欢
product = {}
for row in reader:
product[row[0]] = {'fruit'=row[1],'price'=row[2],'stock'=row[3]}