【问题标题】:Why does python only read last line of a csv?为什么 python 只读取 csv 的最后一行?
【发布时间】:2015-05-16 10:32:17
【问题描述】:

这就是 csv 的样子

2015-05-16,3.99 2015-05-16,4.0

这是代码,它试图将 csv 转换为 dict:

with open('log.csv') as filename:
    reader  = csv.reader(filename,delimiter=',') #fieldnames=['Date','GPA'] 
    display = {row[0]:row[1] for row in reader}
    print display

输出:

$python test.py
{'2015-05-16': 4.0}

它应该是这样的:

$ python test.py
{'2015-05-16':3.99,'2015-05-16': 4.0}

【问题讨论】:

    标签: python csv io


    【解决方案1】:

    您不能这样做:字典需要有不同的键,而您的 CSV 有两个具有相同键的条目(5 月 16 日)。

    如果您更改 log.csv,您的代码将按预期工作:

    {'2015-05-16': '3.99', '2015-05-17': '4.0'}
    

    您可以做一些事情来使键不同,例如添加行号:

    display = { (row[0], i):row[1] for i, row in enumerate(reader) }
    

    会输出

    {('2015-05-16', 0): '3.99', ('2015-05-16', 1): '4.0'}
    

    或者你可以使用一个 array 的字典(并获得不同的输出,但现在包含所有数据):

    display = [ { row[0]:row[1] } for row in reader ]
    
    [{'2015-05-16': '3.99'}, {'2015-05-16': '4.0'}]
    

    或者您可以尝试将同一键的所有值分组在一起,例如

    {
        '2015-05-16': [ '3.99', '4.0' ],
        '2015-05-17': [ '3.14159' ]
    }
    

    但除此之外,字典中每个相同的键都会覆盖之前出现的任何键,因此您将始终“看到”最后一个键。

    【讨论】:

      【解决方案2】:

      当您尝试在 dict 中为现有键插入不同的值时,它会覆盖以前的值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 2022-09-23
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多