为什么我的python字典排序功能不起作用?

时间:2015-11-09 04:52:16

标签: python python-2.7

这段代码应该根据每个键的值对字典进行排序。 函数将列表中的每个元素(字典列表)与索引(x)与索引(x + 1)的元素进行比较。如果它更小则更改位置。

def srt(dic):
    Als= list()
    Bls= list()
    ls = dic.keys()

    glenth = len (ls)
    count=0
    t=0
    while t < 200000:
        for x in range(0,len(ls)):
            count +=1
            A_value = dic[(ls[x])]

            if count >= len(ls):
                B_value = dic[(ls[count-1])]
                count -=1
            else:
                B_value = dic[(ls[count])]
            if A_value > B_value:
                continue
            else:
                A = ls[count-1]
                B = ls[count]
                ls[count-1] = B
                ls[count]  = A
    t +=1

    return ls

dic = dict()
dic = {'baraa':4,'Mohamed':30,'ali':40,'Mirghani':7,'Abuzaid':12,'ElonMask':3,'Jobs':1}
lst = srt(dic)
for x in lst:
    print x,dic[x]

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找OrderedDict。

from collections import OrderedDict

dic ={'baraa':4,'Mohamed':30,'ali':40,'Mirghani':7,'Abuzaid':12,'ElonMask':3,'Jobs':1}
ordered_dic = OrderedDict(sorted(dic.items(), key=lambda t:t[1]))
print ordered_dic

输出:

OrderedDict([('Jobs', 1), ('ElonMask', 3), ('baraa', 4), ('Mirghani', 7), ('Abuzaid', 12), ('Mohamed', 30), ('ali', 40)])

ordered_dic按dic的值排序,然后将其用作普通字典。例如:

for k, v in ordered_dic.items():
    print k, v

这会给你:

Jobs 1
ElonMask 3
baraa 4
Mirghani 7
Abuzaid 12
Mohamed 30
ali 40