【问题标题】:List to dict: incorrectly sorted resultList to dict:错误排序的结果
【发布时间】:2015-10-16 22:48:51
【问题描述】:

我尝试对此进行排序

{1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

到这里

{3: 4, 4: 3, 1: 2, 2: 1, 0: 0}

使用 a:b 模型,其中按最高 b 值排序

import operator

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)

print(sorted_x)

第一个结果很好,但是是列表形式:

[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]

我尝试过

print(dict(sorted_x))

但是……

{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}

如何保存正确排序的结果并将其转换为 dict 格式? 非常感谢

更新:

OrderedDict([(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)])

我不明白 OrderedDict 如何解决我的问题

【问题讨论】:

标签: python sorting


【解决方案1】:

无法订购字典。但是你可以使用collections.OrderedDict类。

【讨论】:

    【解决方案2】:
    >>> from collections import OrderedDict
    >>> sorted_dict = OrderedDict()
    >>> dct = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
    >>> dct.values().sort()
    >>> for x in sorted(dct.values(), reverse=True):
    ...     keys = [idx for idx in dct if dct[idx]==x]
    ...     for key in keys:
    ...         sorted_dict[key] = x
    ... 
    >>> 
    >>> sorted_dict
    OrderedDict([(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)])
    >>> 
    

    或者,如果您一心想将一些看起来像 dict 语法的东西写入文件,

    >>> def print_dict_looking_thing(ordered_dict):
    ...     print "{"
    ...     for key, value in ordered_dict.iteritems():
    ...         print "{0}: {1},".format(key, value)
    ...     print "}"
    ... 
    >>> print_dict_looking_thing(sorted_dict)
    {
    3: 4,
    4: 3,
    1: 2,
    2: 1,
    0: 0,
    }
    

    这就是 OrderedDict “解决您的问题”的方式。但是,有几点值得再次强调:

    1. 字典是无序的。您不能“对它们进行排序”,只能对它们的键和值进行操作。
    2. OrderedDicts 记住添加项目的顺序。
    3. 听起来您正试图将一些看起来像 dict 语法的文件打印到文件中。如果你这样做并在某个时候将 dict 读入 python,它将再次成为一个无序对象(一个 dict)
    4. 目前还不清楚“您的问题”是什么。期望的最终状态是什么;打印一个读起来像 dict 语法的字符串?制作具有 dicts 的访问器方法的东西?明确您到底想要什么(在性能方面)会很有帮助。
    5. 上面的代码复杂度为 O(n**2)。不要在大事上使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2015-12-19
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多