2015-05-16 117 views
-1

这是CSV看起来像为什么python只能读取csv的最后一行?

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

这里是代码,它试图将CSV转换成字典:

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} 

回答

2

你不能这样做:一个字典需要有不同的密钥,并且你的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'} 

或者你可以使用一个数组类型的字典的(一ND得到不同的结果,但现在所有的数据):

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' ] 
} 

但是,否则,词典中的每个相同的键将覆盖以前的任何事件,以便您总是只能看到最后一个。

0

当您尝试在字典中插入现有密钥的不同值时,它会覆盖以前的值

相关问题