python dictionary sorting in descending order based on values
You can use the operator to sort the dictionary by values in descending order.
import operator
d = {"a":1, "b":2, "c":3}
cd = sorted(d.items(),key=operator.itemgetter(1),reverse=True)
The Sorted dictionary will look like,
cd = {"c":3, "b":2, "a":1}
Here, operator.itemgetter(1) takes the value of the key which is at the index 1.
Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you're trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes
A short example to sort dictionary is desending order for Python3.
a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
print(r, a1[r])
Following will be the output
e 30
b 13
d 4
c 2
a 1
Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.
In different terms, your d
and your e
would be exactly equivalent dictionaries.
What you can do here is to use an OrderedDict
:
from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
key=lambda kv: kv[1]['key3'], reverse=True))
The original d
has some arbitrary order. d_ascending
has the order you thought you had in your original d
, but didn't. And d_descending
has the order you want for your e
.
If you don't really need to use e
as a dictionary, but you just want to be able to iterate over the elements of d
in a particular order, you can simplify this:
for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
do_something_with(key, value)
If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict
, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict
that re-sorts itself as necessary, etc.