按值排序字典数据,同时保留唯一键

时间:2017-08-23 21:59:58

标签: python-2.7 sorting dictionary

我创建了一本字典(很大程度上通过反复试验,所以我有点迷失了),如下所示:

{0:' 68651880',993793:' 68656512',29648:' 68671002',325637:' 68656512',282119: ' 68656512',404490:' 68656512',3595:' 68657355',1549:' 68655127',559630:' 68656512&# 39;,3599:' 68657355',3601:' 68657355',435730:' 68656512',241171:' 68656512',4118:& #39; 68657355',439319:' 68656512',403480:' 68656512',349721:' 68656512',40476:' 68660531&#39 ;,337437:' 68656512',20510:' 68671002',4127:' 68657355',505888:' 68656512',459297:&# 39; 68656512',3419:' 68660531',73533:' 68660531',5201:' 68651903',169511:' 68657355' ,450689:' 68656512',22949:' 68671002',26631:' 68671002',16940:' 68671002',9774:&#39 ; 68651903',50735:' 68671002',449073:' 68656512',374322:' 68656512',350263:' 68656512', 2525:' 68655127 ',411195:' 68656512',237630:' 68671002',24639:' 68671002',1417:' 68655127',3649 :' 68657355',404035:' 68656512',409161:' 68656512',330826:' 68656512',3659:' 68657355& #39;,20044:' 68660531',195661:' 68671002',67482:' 68671002',259151:' 68656512',3310: ' 68657355'}

为了帮助您理解,键(第一个值)是以秒为单位的时间量,值(第二个值)是一堆以6开头的作业ID,都是8位数,有时它们会重复自己。

我需要整理数据,这样我才能看到每个作业ID按升序排列的时间。因此,如果作业ID重复,就像其中一些作业ID一样,每个相应的时间(以秒为单位),我想按升序排序该作业ID。

以下是我感兴趣时如何生成数据列表的代码:

#create urlfriendlylist
for item in urlfriendlylist:
    fpp = FarmPageParser("http://farmweb/AnimalFarm/" + item + ".html#subjobs")
    fpp.reset()
    slowjobs = fpp.getFarmTableHTML(4)
    fpp.feed(slowjobs)
    x = fpp.table
    #turn back into jobid
    key = item[0:5] + item[6:9]
    #create dictionary of CPU time and jobid
    for a in x:
        try:
            CPUtime = a[2]
            #use function to convert hh:mm:ss into ssssss
            sec_got = get_sec(CPUtime)
            #populate dictionary with loop
            dic[sec_got] = key
        except: pass
print dic

1 个答案:

答案 0 :(得分:2)

您可以为此创建另一个dict,如下所示:

dic2 = {}
for key, value in dic.iteritems():
    if not value in dic2:
        dic2[value] = []
    dic2[value].append(key)

for lst in dic2:
    lst.sort()

print dic2