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

问题描述 投票:1回答:2

我想通过其值(整数)将字典排序回字典。如下:

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
2个回答
2
投票

Are dictionaries ordered in Python 3.6+?

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

  • 预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}

0
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.