【问题标题】:Convert csv file into dictionary, with chosen keys?使用选定的键将 csv 文件转换为字典?
【发布时间】:2020-12-17 09:54:15
【问题描述】:

我基本上是在尝试使用我自己的命名键将 csv 文件转换为字典,但由于某种原因我收到了语法错误。我正在使用最新的 Python 顺便说一句。 下面是 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 新手,我仍在努力学习。 谢谢大家!

【问题讨论】:

    标签: python python-3.x csv dictionary


    【解决方案1】:

    你的语法确实错了。

    你可能正在寻找

    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)
    

    【讨论】:

    • 啊,是的,我使用 = 而不是:这是一个快速修复,非常感谢!
    【解决方案2】:

    在处理 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)
    

    【讨论】:

    • 是的,我犯了一个愚蠢的语法错误。感谢您指出!
    【解决方案3】:

    你应该这样做

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

    【讨论】:

    • 语法仍然无效。字典键和值用冒号分隔。
    猜你喜欢
    • 2017-03-27
    • 2019-07-18
    • 1970-01-01
    • 2016-01-28
    • 2021-03-23
    • 2018-01-14
    • 2021-12-22
    • 2017-09-13
    • 2014-03-01
    相关资源
    最近更新 更多