Reputation: 143
My code:
abc = {
'Name':emp_name,
'Id no':emp_idno,
'Leave taken':k,
'Leave reqd':b,
'Total days of leave':total,
'Reason':reason
}
I am getting output as:
id, name, total, reqason, leave taken, leave reqd
I want the output to be in this order:
Name, id, leave taken, leave reqd, total, reason
I am stuck up with this and it would be great if anyone can help me out.
my codes for csv
dl = {'Name':emp_name,'Id no':emp_idno, 'Leave taken':k, 'Leave
> reqd':b, 'Reason':reason}
>
>
> key_list = ['Name', 'Id no', 'Leave taken', 'Leave reqd', 'Reason'] abc = { 'Name':emp_name, 'Id no':emp_idno, 'Leave taken':k,
> 'Leave reqd':b, 'Reason':reason }
>
> for k in key_list:
> print abc[k] Lst.append(k)
>
> keys = Lst[0].keys() with open('employee.csv', 'wb') as output_file:
> dict_writer = csv.DictWriter(output_file, keys)
> dict_writer.writeheader()
> dict_writer.writerows(Lst)
Upvotes: 0
Views: 356
Reputation: 4330
one simple hack can be storing the keys in a list.
key_list = ['Name', 'Id no', 'Leave taken', 'Leave reqd', 'Total days of leave', 'Reason']
abc = {
'Name':emp_name,
'Id no':emp_idno,
'Leave taken':k,
'Leave reqd':b,
'Total days of leave':total,
'Reason':reason
}
for k in key_list:
print abc[k]
Upvotes: 0
Reputation: 2930
Dictionaries
are unordered by default.
You need an ordered
Dicitionary
.
see collections.OrderedDict
eg:
from collections import OrderedDict
d = OrderedDict()
d['Name'] = emp_name
d['Id no'] = emp_idno
d['Leave taken'] = k
print d
Upvotes: 2