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

Sorting a Python 3 Dictionary by values back to Dictionary not a List of Tuples

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

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

你可以试试这个:

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}