【发布时间】:2017-04-26 06:06:40
【问题描述】:
def positive(self):
total = {}
final = {}
for word in envir:
for i in self.lst:
if word in i:
if word in total:
total[word] += 1
else:
total[word] = 1
final = sorted(total, reverse = True)
return total
返回
{'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
我想把这本字典恢复成一个有序的字典。我如何排序并返回字典?
【问题讨论】:
-
为什么要对字典进行排序?您无法对字典进行排序。
-
使用
collections.OrderedDict,我认为在Python 3.6 普通字典变得有序。 -
你想返回final吗?
-
Python 实际上有一个 OrderedDict。但是它不能按任意函数排序,它只保留其原始插入顺序。一个更复杂的相关问题:How to sort OrderedDict in OrderedDict - Python?
-
相关:@JacquesdeHooge 对Sorting OrderedDict not working的回答
标签: python sorting dictionary ordereddictionary