将变量存储在字典中并按降序排序

时间:2015-03-21 12:11:42

标签: python dictionary

在我的代码中,我如何在字典中按顺序存储和排序。

我希望将Item存储为关键字,并将Mutual_information存储为值,并在字典中根据Mutual_information数值以降序存储它们。

我的编码,包含变量itemMutual_information

for item in lines:
    specificy = c[item]
    try:
        MI1= specificy/float(specificx)
        MI2= MI1*specificx
        M13= specificx*specificx
        Mutual_Information = MI1* math.log(MI1/float(MI2))
        print item, Mutual_Information #to be stored in descendin
    except ZeroDivisionError:
        print "divide by zero"    

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的那样,dicts是无序的,因此这将获得列表中的所有项目,然后按相反的顺序排序并从这些已排序的元素创建OrderedDict

from collections import OrderedDict
from operator import itemgetter

# store all key,value pairings to sort later
items = []
for item in lines:
    specificy = c[item]
    try:
        MI1= specificy/float(specificx)
        MI2= MI1*specificx
        M13= specificx*specificx
        Mutual_Information = MI1* math.log(MI1/float(MI2))
        # add tuple of key/value to items
        items.append((item,Mutual_Information))
    except ZeroDivisionError:
        print "divide by zero"

# create OrderedDict from sorted items, sorting by the second element
d = OrderedDict(sorted(items,key=itemgetter(1),reverse=True))

使用元组列表的示例:

from collections import OrderedDict

items = [(1, 3), (4, 7), (2, 4), (6, 10)]
from operator import itemgetter

d = OrderedDict(sorted(items, key=itemgetter(1), reverse=True))
print(d)
OrderedDict([(6, 10), (4, 7), (2, 4), (1, 3)])