sort dict by value python

PythonDictionaryPython 2.6

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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: https://stackoverflow.com/q/39980323/174728

Solution 2 - Python

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

Solution 3 - Python

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])

Solution 4 - Python

Sort the values:

sorted(data.values())

returns

['a','b']

Solution 5 - Python

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]

Solution 6 - Python

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.

Solution 7 - Python

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

Solution 8 - Python

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)

Solution 9 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkingRaukView Question on Stackoverflow
Solution 1 - PythonJohn La RooyView Answer on Stackoverflow
Solution 2 - PythonjamylakView Answer on Stackoverflow
Solution 3 - Pythonnjzk2View Answer on Stackoverflow
Solution 4 - PythoneumiroView Answer on Stackoverflow
Solution 5 - PythonkingRaukView Answer on Stackoverflow
Solution 6 - PythonMorgan WildeView Answer on Stackoverflow
Solution 7 - PythonMariusView Answer on Stackoverflow
Solution 8 - PythonChristian LongView Answer on Stackoverflow
Solution 9 - PythonxiyuruiView Answer on Stackoverflow