I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.
I can sort on the keys, but how can I sort based on the values?
Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.
Use ValueSortedDict from dicts:
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
12
is smaller than20
(which is not the case in string comparison). So I came up with the following. When you want explicit numeric comparison you can use the flagnum_as_num
which will try to do explicit numeric sorting by trying to convert all values to floats. If that succeeds, it will do numeric sorting, otherwise it'll resort to string comparison.Comments for improvement or push requests welcome.
I came up with this one,
For Python 3.x:
x.items()
replacingiteritems()
.Or try with
collections.OrderedDict
!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:
If values are numeric you may also use Counter from collections
If your values are integers, and you use Python 2.7 or newer, you can use
collections.Counter
instead ofdict
. Themost_common
method will give you all items, sorted by the value.