【问题标题】:Sorting a Python 3 Dictionary by values back to Dictionary not a List of Tuples按值将 Python 3 字典排序回字典而不是元组列表
【发布时间】:2019-07-19 04:12:48
【问题描述】:

我想按字典的值(整数)将字典排序回字典。如下:

di = {'h': 10, 'e':5, 'l':8}

我想要的是:

sorted_di = {'e':5, 'l':8, 'h':10}

我搜索了很多并将其排序到元组列表中,例如:

import operator
sorted_li = sorted(di.items(),key=operator.itemgetter(1),reverse=True)
print(sorted_li)

给:

[('e',5),('l':8),('h':10)]

但我希望它再次成为字典。

谁能帮帮我吗?

【问题讨论】:

    标签: python sorting dictionary python-3.5 key-value


    【解决方案1】:

    Are dictionaries ordered in Python 3.6+?

    它们是插入排序的。从 Python 3.6 开始,对于 CPython Python的实现,字典记住项目的顺序 插入。这被认为是 Python 3.6 中的一个实现细节; 如果你想要插入排序,你需要使用OrderedDict 保证跨 Python 的其他实现(和其他有序 行为)。

    • 3.6 之前:

      >>> from collections import OrderedDict
      ...
      >>> OrderedDict(sorted_li)
      OrderedDict([('e', 5), ('l', 8), ('h', 10)])
      
    • 3.6+:

      >>> dict(sorted_li)
      {'e':5, 'l':8, 'h':10}
      

    【讨论】:

    • 我相信他们将其从实现细节更改为 Python 3.7 中的保证。
    • @FightWithCode OrderedDict 字典,打印时它只是看起来像元组。
    • 好吧,我明白了。首先将字典排序到元组列表中。然后通过 OrderedDict 将其转换为 dict。非常感谢你
    • @FightWithCode 您应该在问题正文中包含排序代码;我的回答是为了描述下一步。
    • 如你所愿。
    【解决方案2】:
    di = {'h': 10, 'e':5, 'l':8}
    temp_list = []
    for key,value in di.items():
        temp_tuple = (k,v)
        temp_list.append(temp_tuple)
    temp_list.sort()
    for x,y in temp_list:
        dict_sorted = dict(temp_list)
    print(dict_sorted)
    

    【讨论】:

    • 不鼓励在 SO 上仅提供代码答案。请补充您提供的代码作为答案,说明为什么它可以解决 OP 的问题。
    【解决方案3】:

    你可以试试这个:

    di = {'h': 10, 'e':5, 'l':8}
    tuples = [(k, di[k]) for k in sorted(di, key=di.get, reverse=False)]
    sorted_di = {}
    for i in range(len(di)):
        k = tuples[i][0]
        v = tuples[i][1]
        sorted_di.update({k: v})
    print(sorted_di)  # {'e': 5, 'l': 8, 'h': 10}
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2018-10-19
      • 2014-06-24
      • 1970-01-01
      • 2011-02-22
      相关资源
      最近更新 更多