Sort dictionary by value python
Python 3.7+ or CPython 3.6Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail. Show
or
Older PythonIt is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples. For instance,
And for those wishing to sort on keys instead of values:
In Python3 since unpacking is not allowed we can use
If you want the output as a dict, you can use
wjandrea 24.4k8 gold badges51 silver badges71 bronze badges answered Mar 5, 2009 at 0:59
Devin JeanpierreDevin Jeanpierre 89.6k4 gold badges54 silver badges79 bronze badges 10 As simple as: sorted(dict1, key=dict1.get)Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency. If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:
then you can get a list of the words, ordered by frequency of use with
I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.
answered Jul 5, 2010 at 8:01
3 You could use:
This will sort the dictionary by the values of each entry within the dictionary from smallest to largest. To sort it in descending order just add
Input:
Output:
Suresh2692 3,6433 gold badges15 silver badges25 bronze badges answered Feb 13, 2010 at 16:33
MarkMark 11.1k1 gold badge14 silver badges5 bronze badges 6 Dicts can't be sorted, but you can build a sorted list from them. A sorted list of dict values:
A list of (key, value) pairs, sorted by value:
answered Mar 5, 2009 at 1:05
3 In recent Python 2.7, we have the new OrderedDict type, which remembers the order in which the items were added.
To make a new ordered dictionary from the original, sorting by the values:
The OrderedDict behaves like a normal dict:
answered Jul 5, 2010 at 2:50
mykhalmykhal 18.5k11 gold badges71 silver badges78 bronze badges 7 UPDATE: 5 DECEMBER 2015 using Python 3.5 Whilst I found the accepted answer useful, I was also surprised that it hasn't been updated to reference OrderedDict from the standard library collections module as a viable, modern alternative - designed to solve exactly this type of problem.
The official OrderedDict documentation offers a very similar example too, but using a lambda for the sort function:
answered Dec 5, 2015 at 9:46
arcseldonarcseldon 33.5k15 gold badges117 silver badges120 bronze badges 1 Pretty much the same as Hank Gay's answer:
Or optimized slightly as suggested by John Fouhy:
answered Mar 5, 2009 at 1:06
user26294user26294 5,2073 gold badges21 silver badges18 bronze badges 4 As of Python 3.6 the built-in dict will be orderedGood news, so the OP's original use case of mapping pairs retrieved from a database with unique string ids as keys and numeric values as values into a built-in Python v3.6+ dict, should now respect the insert order. If say the resulting two column table expressions from a database query like:
would be stored in two Python tuples, k_seq and v_seq (aligned by numerical index and with the same length of course), then:
Allow to output later as:
yielding in this case (for the new Python 3.6+ built-in dict!):
in the same ordering per value of v. Where in the Python 3.5 install on my machine it currently yields:
Details:As proposed in 2012 by Raymond Hettinger (cf. mail on python-dev with subject "More compact dictionaries with faster iteration") and now (in 2016) announced in a mail by Victor Stinner to python-dev with subject "Python 3.6 dict becomes compact and gets a private version; and keywords become ordered" due to the fix/implementation of issue 27350 "Compact and ordered dict" in Python 3.6 we will now be able, to use a built-in dict to maintain insert order!! Hopefully this will lead to a thin layer OrderedDict implementation as a first step. As @JimFasarakis-Hilliard indicated, some see use cases for the OrderedDict type also in the future. I think the Python community at large will carefully inspect, if this will stand the test of time, and what the next steps will be. Time to rethink our coding habits to not miss the possibilities opened by stable ordering of:
The first because it eases dispatch in the implementation of functions and methods in some cases. The second as it encourages to more easily use Raymond Hettinger kindly provided documentation explaining "The Tech Behind Python 3.6 Dictionaries" - from his San Francisco Python Meetup Group presentation 2016-DEC-08. And maybe quite some Stack Overflow high decorated question and answer pages will receive variants of this information and many high quality answers will require a per version update too. Caveat Emptor (but also see below update 2017-12-15):As @ajcr rightfully notes: "The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon." (from the whatsnew36) not nit picking, but the citation was cut a bit pessimistic ;-). It continues as " (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5)." So as in some human languages (e.g. German), usage shapes the language, and the will now has been declared ... in whatsnew36. Update 2017-12-15:In a mail to the python-dev list, Guido van Rossum declared:
So, the version 3.6 CPython side-effect of dict insertion ordering is now becoming part of the language spec (and not anymore only an implementation detail). That mail thread also surfaced some distinguishing design goals for answered Sep 10, 2016 at 10:05
DilettantDilettant 3,1693 gold badges29 silver badges28 bronze badges 3 It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values and you want to sort on 'score':
sorting with lowest score first:
sorting with highest score first:
Now you can get the name and score of, let's say the second-best player (index=1) very Pythonically like this:
vallentin 21.8k6 gold badges55 silver badges75 bronze badges answered Aug 30, 2011 at 0:30
RemiRemi 19.9k8 gold badges55 silver badges41 bronze badges 2 I had the same problem, and I solved it like this:
(People who answer "It is not possible to sort a dict" did not read the question! In fact, "I can sort on the keys, but how can I sort based on the values?" clearly means that he wants a list of the keys sorted according to the value of their values.) Please notice that the order is not well defined (keys with the same value will be in an arbitrary order in the output list).
answered Nov 18, 2010 at 14:19
jimifikijimifiki 5,2241 gold badge32 silver badges56 bronze badges 2 If values are numeric you may also use
Georgy 10.7k7 gold badges61 silver badges68 bronze badges answered Jun 27, 2012 at 15:43
Ivan SasIvan Sas 9831 gold badge9 silver badges14 bronze badges 2 In Python 2.7, simply do:
copy-paste from : http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes Enjoy ;-) answered Aug 22, 2013 at 8:38
sweetdreamsweetdream 1,17111 silver badges13 bronze badges This is the code:
Here are the results: Original
Rofl
Rank
icedwater 4,5423 gold badges33 silver badges47 bronze badges answered Mar 8, 2011 at 2:06
PedroMorganPedroMorgan 89812 silver badges15 bronze badges Try the following approach. Let us define a dictionary called mydict with the following data:
If one wanted to sort the dictionary by keys, one could do something like:
This should return the following output:
On the other hand, if one wanted to sort a dictionary by value (as is asked in the question), one could do the following:
The result of this command (sorting the dictionary by value) should return the following:
answered Apr 7, 2014 at 4:46
Nathaniel PayneNathaniel Payne 2,7191 gold badge26 silver badges32 bronze badges 2 Starting from Python 3.6,
Before that, you had to use Python 3.7 documentation says:
answered Sep 15, 2018 at 13:37
Maxime ChéramyMaxime Chéramy 16.7k7 gold badges52 silver badges74 bronze badges 1 You can create an "inverted index", also
Now your inverse has the values; each value has a list of applicable keys.
answered Mar 5, 2009 at 1:52
S.LottS.Lott 376k78 gold badges502 silver badges771 bronze badges You can use the collections.Counter. Note, this will work for both numeric and non-numeric values.
answered Mar 9, 2013 at 12:30
AbhijitAbhijit 59.9k18 gold badges125 silver badges197 bronze badges 1 You can use a skip dict which is a dictionary that's permanently sorted by value.
If you use It's implemented using the skip list datastructure. answered Sep 25, 2014 at 22:56
malthemalthe 97510 silver badges21 bronze badges 2 The collections solution mentioned in another answer is absolutely superb, because you retain a connection between the key and value which in the case of dictionaries is extremely important. I don't agree with the number one choice presented in another answer, because it throws away the keys. I used the solution mentioned above (code shown below) and retained access to both keys and values and in my case the ordering was on the values, but the importance was the ordering of the keys after ordering the values.
answered Mar 3, 2014 at 14:58
Eamonn KennyEamonn Kenny 1,69116 silver badges17 bronze badges 0 You can also use custom function that can be passed to key.
Georgy 10.7k7 gold badges61 silver badges68 bronze badges answered May 25, 2017 at 18:13
1 Of course, remember, you need to use
If you do not have Python 2.7 or higher, the best you can do is iterate over the values in a generator function. (There is an a) I don't know about how well it works and b) You have to download and install it of course. If you do not have administrative access, then I'm afraid the option's out.)
You can also print out every value
Please remember to remove the parentheses after print if not using Python 3.0 or above
Georgy 10.7k7 gold badges61 silver badges68 bronze badges answered Jul 31, 2015 at 8:08
rassa45rassa45 3,4061 gold badge28 silver badges43 bronze badges 1
answered Nov 1, 2010 at 12:16
ArgunArgun 4175 silver badges20 bronze badges 1 Here is a solution using zip on
So we can do the following:
answered Jun 20, 2015 at 1:44
ScottScott 5,7114 gold badges34 silver badges50 bronze badges 0 As pointed out by Dilettant, Python 3.6 will now keep the order! I thought I'd share a function I wrote that eases the sorting of an iterable (tuple, list, dict). In the latter case, you can sort either on keys or values, and it can take numeric comparison into account. Only for >= 3.6! When you try using sorted on an iterable that holds e.g. strings as well as ints, sorted() will fail. Of course you can force string comparison with str(). However, in some cases you want to do actual numeric
comparison where Comments for improvement welcome.
answered Mar 2, 2018 at 16:48
Bram VanroyBram Vanroy 25.6k23 gold badges125 silver badges221 bronze badges Just learned relevant skill from Python for Everybody. You may use a temporary list to help you to sort the dictionary:
If you want to sort the list in descending order, simply change the original sorting line to:
Using list comprehension, the one liner would be:
Sample Output:
answered May 27, 2018 at 17:45
mcgagmcgag 1951 silver badge13 bronze badges 1 Use ValueSortedDict from dicts:
answered Oct 19, 2011 at 6:25
pontyponty 6148 silver badges8 bronze badges Iterate through a dict and sort it by its values in descending order:
answered Oct 30, 2011 at 19:42
juhohjuhoh 1091 silver badge2 bronze badges If your values are integers, and you use Python 2.7 or newer, you can use answered Jan 24, 2012 at 19:28
Petr ViktorinPetr Viktorin 63.5k8 gold badges79 silver badges79 bronze badges This works in 3.1.x:
answered Nov 16, 2011 at 7:32
iFailiFail 891 silver badge1 bronze badge For the sake of completeness, I am posting a solution using heapq. Note, this method will work for both numeric and non-numeric values
answered Mar 23, 2013 at 14:19
AbhijitAbhijit 59.9k18 gold badges125 silver badges197 bronze badges Not the answer you're looking for? Browse other questions tagged python sorting dictionary or ask your own question.Can you sort a dictionary by value in Python?To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.
How do you sort a dictionary in a list in Python by value?To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
Can you sort values in a dictionary?It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
How do you sort the dictionary on the basis of the value?Need for Sorting in Dictionary. First, sort the keys alphabetically using key_value. iterkeys() function.. Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.. Third, sort the values alphabetically using key_value. iteritems(), key = lambda (k, v) : (v, k)). |