简体   繁体   English

使用选择的键将 csv 文件转换为字典?

[英]Convert csv file into dictionary, with chosen keys?

I'm basically trying to convert a csv file into a dictionary with my own named keys, but I'm getting Syntax Error for some reason.我基本上是在尝试使用我自己的命名键将 csv 文件转换为字典,但由于某种原因我收到了语法错误。 I'm using the latest Python btw.我正在使用最新的 Python 顺便说一句。 Here's what the csv file looks like: csv 文件如下所示:

1|apple|0.50|60
2|orange|0.4|55
3|mango|0.6|33

I want to create a dictionary of this form for each fruit:我想为每种水果创建一个这种形式的字典:

dictionary={
'1':{'fruit':'apple',
     'price':0.5,
     'stock':60},
'2':{...},
'3':{...},
}

Here's my attempt:这是我的尝试:

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)

But this doesn't seem to work:( I'm new to Python and I'm still trying to learn. Thanks everyone!但这似乎不起作用:(我是 Python 的新手,我仍在努力学习。谢谢大家!

Your syntax is indeed wrong.你的语法确实是错误的。

You're probably looking for您可能正在寻找

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)

While dealing with CSVs we use '=' instead of ':'.在处理 CSV 时,我们使用 '=' 而不是 ':'。 Your syntax is wrong.你的语法是错误的。 Try this.尝试这个。

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)

You should do like that你应该这样做

product = {}
for row in reader:
   product[row[0]] = {'fruit'=row[1],'price'=row[2],'stock'=row[3]}

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

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