根据特定顺序在dict中排序键

时间:2017-03-03 06:12:38

标签: python list dictionary key

我的代码:

abc = {
   'Name':emp_name,
   'Id no':emp_idno, 
   'Leave taken':k, 
   'Leave reqd':b,
   'Total days of leave':total, 
   'Reason':reason
}

我的输出为:

id, name, total, reqason, leave taken, leave reqd

我希望输出符合以下顺序:

Name, id, leave taken, leave reqd, total, reason

我对此感到困惑,如果有人能帮助我,那就太好了。

我的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)

2 个答案:

答案 0 :(得分:2)

默认情况下,

Dictionaries是无序的。

您需要ordered Dicitionary

请参阅collections.OrderedDict

例如:

from collections import OrderedDict
d = OrderedDict()
d['Name'] = emp_name
d['Id no'] = emp_idno
d['Leave taken'] = k
print d

答案 1 :(得分:0)

一个简单的黑客可以将密钥存储在列表中。

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]