import csv
with open('foo.csv') as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
a = [dict(zip(header, map(int, row))) for row in reader]
print a
# similar solution via namedtuple:
import csv
from collections import namedtuple
with open('foo.csv') as f:
fh = csv.reader(open(f, "rU"), delimiter=',', dialect=csv.excel_tab)
headers = fh.next()
Row = namedtuple('Row', headers)
list_of_dicts = [Row._make(i)._asdict() for i in fh]
a = []
with open("csv.txt") as myfile:
firstline = True
for line in myfile:
if firstline:
mykeys = "".join(line.split()).split(',')
firstline = False
else:
values = "".join(line.split()).split(',')
a.append({mykeys[n]:values[n] for n in range(0,len(mykeys))})
with open('/home/mitul/Desktop/OPENEBS/test.csv', 'rb') as infile:
header = infile.readline().split(",")
for line in infile:
fields = line.split(",")
entry = {}
for i,value in enumerate(fields):
entry[header[i].strip()] = value.strip()
data.append(entry)
output = []
with open("test.csv", "r") as csv_file:
data = csv_file.read().split("\n")
text = [data[i].split(",") for i in range(len(data))]
for i in range(1, len(text)) :
output.append({text[0][num]:text[i][num] for num in range(len(text[i]))})
8条答案
按热度按时间xjreopfe1#
使用
csv.DictReader
:将导致:
jhiyze9q2#
另一个更简单的答案:
7xzttuei3#
使用
csv
模块和列表解析:输出:
guykilcj4#
很久之后才在这里回答,因为我没有看到任何更新/相关的答案。
sc4hvdpw5#
tpgth1q76#
好吧,当其他人用聪明的方式来做的时候,我很天真地实现了它。我想我的方法的好处是不需要任何外部模块,尽管它可能会因为奇怪的值配置而失败。这里只是供参考:
pjngdqdw7#
将CSV解析为字典列表的简单方法
3pmvbmvn8#
我对你的问题的解决方案:
输出是dico的列表