按值排序

假设我有结论。

data = {1:'b', 2:'a'}

我想按照“ b”和“ a”对数据进行排序,这样我就得到了结果

'a','b'

我该怎么做?
有什么想法吗?

289859 次浏览

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+

Sort the values:

sorted(data.values())

returns

['a','b']

I also think it is important to note that Python dict object 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 dict item retrieval in constant time O(1), no matter the size/number of elements in a dictionary.

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:

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.

If you actually want to sort the dictionary instead of just obtaining a sorted list use 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']

From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:

sorted(data.items(), key=lambda x:x[1])

Thanks for all answers. You are all my heros ;-)

Did in the end something like this:

d = sorted(data, key = data.get)


for key in d:
text = data[key]

In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.

PEP 256 suggests this for sorting a dictionary by values.

import operator
sorted(d.iteritems(), key=operator.itemgetter(1))

If you want descending order, do this

sorted(d.iteritems(), key=itemgetter(1), reverse=True)

no lambda method

# 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 ('=======================')

You could created sorted list from Values and rebuild the dictionary:

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'}