sort dict by value python
Assume that I have a dict.
data = {1:'b', 2:'a'}
And I want to sort data by 'b' and 'a' so I get the result
'a','b'
How do I do that?
Any ideas?
To get the values use
sorted(data.values())
To get the matching keys, use a key
function
sorted(data, key=data.get)
To get a list of tuples ordered by value
sorted(data.items(), key=lambda x:x[1])
Related: see the discussion here: Dictionaries are ordered in Python 3.6+
如果你真的想对字典进行排序而不是仅仅获得一个排序列表,可以使用collections.OrderedDict
>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']
从你的评论到gnibbler答案,我想说你想要一个按值排序的键值对列表:
sorted(data.items(), key=lambda x:x[1])
链接地址: http://www.djcxy.com/p/2984.html
上一篇: 建立给定文本中最常用单词的ASCII图表
下一篇: 按值python排序字典