将DictReader
字段(dict 键)存储在名为的属性中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