我有一个包含内容(例子)的.csv文件
Attributes,Description,Dial-Up
4,2,0.2
3,1,0.4
使用dictreader:
dictreader = csv.DictReader(open(filename, "rb"), delimiter=',')
dictdata = {}
count=0
for row in dictreader:
dictdata[count]=row
count=count+1
显示在表格中或使用作者我将得到:
Dial-Up,Attributes,Description
0.2,4,2
0.4,3,1
那么我该如何对字段名进行排序?
答案 0 :(得分:5)
DictReader
将字段(字典键)存储在名为fieldnames
的属性中:
fields = dictreader.fieldnames
print(fields)
# ['Attributes', 'Description', 'Dial-Up']
所以按此顺序打印行值:
print(','.join(fields))
for row in dictreader:
print(','.join(row[field] for field in fields))
产量
Attributes,Description,Dial-Up
4,2,0.2
3,1,0.4
或者,使用@JonClements的想法:
import operator
fields = dictreader.fieldnames
getfields = operator.itemgetter(*fields)
for row in dictreader:
print(','.join(getfields(row)))
使用operator.itemgetter
的动机是它比使用列表理解更快:
In [70]: %timeit getfields(row)
10000000 loops, best of 3: 174 ns per loop
In [71]: %timeit [row[field] for field in fields]
1000000 loops, best of 3: 272 ns per loop