【问题标题】:How to make a dictionary retain its sort order?如何使字典保留其排序顺序?
【发布时间】:2017-04-26 06:06:40
【问题描述】:
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

返回

{'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}

我想把这本字典恢复成一个有序的字典。我如何排序并返回字典?

【问题讨论】:

标签: python sorting dictionary ordereddictionary


【解决方案1】:

一个有序的字典会给你你需要的东西

from collections import OrderedDict

如果您想按字典顺序订购商品,请执行以下操作

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]))

od的内容:

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

如果您想准确指定字典的顺序,请将它们存储为元组并按该顺序存储。

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 

od 现在是

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

在使用中,它就像一本普通的字典,但指定了其内部内容的顺序。

【讨论】:

    【解决方案2】:

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

    unordered = (('climate', 10,), ('ecosystem', 1)) # etc

    在上面调用sorted(unordered) 将返回它,'key' 是每个单独元组中的第一项。在这种情况下,您无需向 sorted() 提供任何其他参数。

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

    【讨论】:

    • OP 显然在寻找collections.OrderedDict。告诉他们dict 不支持键顺序是没有帮助的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多