I have a .csv file with the content (example)
Attributes,Description,Dial-Up
4,2,0.2
3,1,0.4
Using the dictreader:
dictreader = csv.DictReader(open(filename, "rb"), delimiter=',')
dictdata = {}
count=0
for row in dictreader:
dictdata[count]=row
count=count+1
And display in table or using writer i will get:
Dial-Up,Attributes,Description
0.2,4,2
0.4,3,1
So how can i sort the fieldnames?
The DictReader stores the fields (dict keys) in an property called fieldnames:
fields = dictreader.fieldnames
print(fields)
# ['Attributes', 'Description', 'Dial-Up']
So to print the row values in this order:
print(','.join(fields))
for row in dictreader:
print(','.join(row[field] for field in fields))
yields
Attributes,Description,Dial-Up
4,2,0.2
3,1,0.4
Or, using @JonClements' idea:
import operator
fields = dictreader.fieldnames
getfields = operator.itemgetter(*fields)
for row in dictreader:
print(','.join(getfields(row)))
The motivation for using operator.itemgetter would be that it is faster than using a list comprehension:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With