通过python DictReader读取csv中的列表

时间:2014-07-29 18:42:36

标签: python csv python-3.x

我的CSV文件如下所示:

YY,XX,ZZ
[14, 18, 13, 0],"[7, 7, 9, 9]",[]

现在我使用dictread:

csv_file = csv.DictReader(open(test_file, 'r'), delimiter=',', quotechar='"')
for line in csv_file:
  a=line

现在我明白了:

print(a)
>> {'XX': '[7, 7, 9, 9 ]', 'YY': '[14, 18, 13, 0 ]', 'ZZ': '[]'}

print(a["XX"])
>> [7, 7, 9, 9]

b=a["XX"]
print(b[0])
>> [

我想从我的csv中读取元素作为字典但是值应该包含在列表中,所以我得到的是7而不是[:

print(a)
>> {'XX': '[7, 7, 9, 9 ]', 'YY': '[14, 18, 13, 0 ]', 'ZZ': '[]'}

print(a["XX"])
>> [7, 7, 9, 9]

b=a["XX"]
print(b[0])
>> 7 <----

我该怎么做?

2 个答案:

答案 0 :(得分:3)

你快到了。

你有像LOOK一样的字符串,但它们是字符串。只需通过ast literal_eval过滤dict中的字符串元素,将其解析回Python列表:

>>> di={'XX': '[7, 7, 9, 9 ]', 'YY': '[14, 18, 13, 0 ]', 'ZZ': '[]'}
>>> import ast
>>> for k in di:
...    di[k]=ast.literal_eval(di[k])
... 
>>> di
{'YY': [14, 18, 13, 0], 'XX': [7, 7, 9, 9], 'ZZ': []}

答案 1 :(得分:1)

import ast

csv_file = csv.DictReader(open(test_file, 'r'), delimiter=',', quotechar='"')

def proc_line(line):
    keys,vals = zip(*line.items())
    return dict(zip(keys,map(ast.literal_eval,vals)) )

for line in map(proc_line,csv_file):
  keys,vals = zip(line.items())
  a=dict(zip(keys,map(ast.literal_eval,vals)) )