我想按字典的值(整数)将字典排序回字典。就像下面这样:
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/