Python 如何使词典保持其排序顺序?

Python 如何使词典保持其排序顺序?,python,sorting,dictionary,ordereddictionary,Python,Sorting,Dictionary,Ordereddictionary,这是回报 def positive(self): total = {} final = {} for word in envir: for i in self.lst: if word in i: if word in total: total[word] += 1 else: total[

这是回报

def positive(self):
    total = {}
    final = {}
    for word in envir:
        for i in self.lst:
            if word in i:
                if word in total:
                    total[word] += 1
                else:
                    total[word] = 1
    final = sorted(total, reverse = True)

    return total

我想把这本词典还给一本整齐的词典。如何排序并返回字典?

Python中的字典没有明确的顺序(3.6中除外)。哈希表中没有“order”属性。要在Python中保持顺序,请使用元组列表:

unordered=(('climate',10,),('economics',1))等

在上面调用
sorted(unordered)
将返回它,“key”是每个元组中的第一项。在本例中,您不需要为
sorted()
提供任何其他参数


要进行迭代,请使用z中的x,y的
,其中
z
是列表。

一个有序的字典可以满足您的需要

{'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
如果要按字典顺序对项目进行排序,请执行以下操作

from collections import OrderedDict
od的内容

d1 = {'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
od = OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
如果您想精确地指定字典的顺序,那么将它们存储为元组并按该顺序存储

OrderedDict([('climate', 10),
             ('ecosystem', 1),
             ('energy', 6),
             ('human', 1),
             ('native', 2),
             ('renewable', 2),
             ('world', 2)])
od
现在是

t1 = [('climate',10), ('ecosystem', 1), ('energy',6), ('human', 1), ('world', 2), ('renewable', 2), ('native', 2)]
od = OrderedDict()

for (key, value) in t1:
    od[key] = value 

在使用过程中,它与普通词典一样,但指定了内部内容的顺序。

为什么要对词典进行排序?您不能对字典进行排序。使用,我认为Python 3.6中的普通字典是有序的。是否要返回final?Python实际上有一个OrderedDict。但是,它不能按任意函数排序,它只保留其原始插入顺序。一个更复杂的相关问题:?相关:@JacquesDehoge对OP的回答显然是寻找
集合。OrderedDict
。告诉他们
dict
不支持键顺序是没有帮助的。
OrderedDict([('climate', 10),
             ('ecosystem', 1),
             ('energy', 6),
             ('human', 1),
             ('world', 2),
             ('renewable', 2),
             ('native', 2)])