python - 按值将 Python 3 字典排序回字典而不是元组列表

标签 python sorting dictionary python-3.5 key-value

我想按字典的值(整数)将字典排序回字典。就像下面这样:

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

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

谁能帮帮我吗?

最佳答案

Are dictionaries ordered in Python 3.6+?

They are insertion ordered. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior).

  • 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 - 按值将 Python 3 字典排序回字典而不是元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871600/

相关文章:

python - 在不将最终副本存储到 HD 的情况下在 Python 中加密/解密动画 gif

xml - 使用 XSLT 对 IP 地址进行排序

Python:如何从字典列表中创建一个 csv 字符串(无文件)?

python - 导致 AttributeError 的多个词典?

python - py2exe 无法生成可执行文件

python - 将数组转换为 Pandas 数据框列

python - Pandas 根据条件返回索引和列名

java - 用两个循环对数组进行排序实现

C++ 排序坐标存储为 vector 中的对象

ios - 如何将 plist 的数据包括字典行到字典数组以在代码上使用它