0

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)
anonymous
  • 143
  • 1
  • 2
  • 16
  • Possible duplicate of [Python dictionary, how to keep keys/values in same order as declared?](http://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-in-same-order-as-declared) – vishes_shell Mar 03 '17 at 06:22

2 Answers2

2

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
Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17
0

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]
Ashish
  • 4,206
  • 16
  • 45
  • When i write this k or d as mithilesh said into a csv file, the output of csv file doesnt follows the list order – anonymous Mar 03 '17 at 06:50
  • i can understand that im trying to write a list as csv instead of dict. just want to know the solution to correct myself – anonymous Mar 03 '17 at 06:54