根据字典的值大小进行排序

# (== get a representation sorted by value)
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# Or:
>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

如果要变成dict形式,可以使用以下

import collections

sorted_dict = collections.OrderedDict(sorted_x)

参考来源:https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value

posted @ 2018-10-09 20:05  bingo彬哥  阅读(2369)  评论(0编辑  收藏  举报
本站总访问量