将Python3字典按值排序回字典而不是元组列表
我想将字典按其值(整数)排序回字典。例如:将Python3字典按值排序回字典而不是元组列表,python,sorting,dictionary,python-3.5,key-value,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)
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 3.6开始,对于CPython
Python实现,字典记住项目的顺序
插入。这被认为是Python 3.6中的一个实现细节;
如果需要插入顺序,则需要使用OrderedDict
在Python的其他实现(以及其他应用程序)中得到保证
行为)
i、 e
- 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}
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}
我相信他们在Python3.7中将其从实现细节更改为保证。@FightWithCode
OrderedDict
是一本字典,打印时它只看起来像元组。现在我明白了。首先,将dict排序到元组列表中。然后通过OrderedDict将其转换为dict。多谢各位much@FightWithCode应在问题正文中包含排序代码;我的回答是为了描述下一步。如你所愿,好吧。不鼓励只回答代码。请补充您作为答案提供的代码,说明它解决OP问题的原因。
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}