按值对字典进行排序python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16772071/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort dict by value python
提问by kingRauk
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
我想按 'b' 和 'a' 对数据进行排序,所以我得到了结果
'a','b'
How do I do that?
Any ideas?
我怎么做?
有任何想法吗?
回答by John La Rooy
To get the values use
要获取值,请使用
sorted(data.values())
To get the matching keys, use a keyfunction
要获取匹配的键,请使用key函数
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+
相关:请参阅此处的讨论:字典在 Python 3.6+ 中排序
回答by eumiro
Sort the values:
对值进行排序:
sorted(data.values())
returns
返回
['a','b']
回答by Morgan Wilde
I also think it is important to note that Python dictobject type is a hash table (more on this here), and thus is not capable of being sorted without converting its keys/values to lists. What this allows is dictitem retrieval in constant time O(1), no matter the size/number of elements in a dictionary.
我还认为重要的是要注意 Pythondict对象类型是一个哈希表(更多关于这个here),因此如果不将其键/值转换为列表,就无法进行排序。这允许dict在恒定时间内检索项目O(1),无论字典中元素的大小/数量如何。
Having said that, once you sort its keys - sorted(data.keys()), or values - sorted(data.values()), you can then use that list to access keys/values in design patterns such as these:
话虽如此,一旦您对其键 -sorted(data.keys())或值 - 进行排序sorted(data.values()),您就可以使用该列表来访问设计模式中的键/值,例如:
for sortedKey in sorted(dictionary):
    print dictionary[sortedKeY] # gives the values sorted by key
for sortedValue in sorted(dictionary.values()):
    print sortedValue # gives the values sorted by value
Hope this helps.
希望这可以帮助。
回答by jamylak
If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict
如果你真的想对字典进行排序而不是仅仅获得一个排序的列表,请使用 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']
回答by njzk2
From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:
从您的评论到 gnibbler 的答案,我想说您想要一个按值排序的键值对列表:
sorted(data.items(), key=lambda x:x[1])
回答by kingRauk
Thanks for all answers. You are all my heros ;-)
感谢所有的答案。你们都是我的英雄;-)
Did in the end something like this:
最后做了这样的事情:
d = sorted(data, key = d.get)
for id in d:
    text = data[id]
回答by Christian Long
In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.
在回复 John 的评论中,您建议您需要字典的键和值,而不仅仅是值。
PEP 256suggests this for sorting a dictionary by values.
PEP 256建议将其用于按值对字典进行排序。
import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
If you want descending order, do this
如果您想要降序,请执行此操作
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
回答by xiyurui
no lambda method
没有 lambda 方法
# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
    for k, v in d.items():
        if v == i:
            return (k)
sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:   
    key = getkeybyvalue(d,i1)
    sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')
回答by Marius
You could created sorted list from Values and rebuild the dictionary:
您可以从 Values 创建排序列表并重建字典:
myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}
newDictionary={}
sortedList=sorted(myDictionary.values())
for sortedKey in sortedList:
    for key, value in myDictionary.items():
        if value==sortedKey:
            newDictionary[key]=value
Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}
输出: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}

