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.
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.
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
How to Sort a Dict in Descending Order by Value With Python
How do I sort dictionary keys by their values?
python - How do I sort a dictionary by value? - Stack Overflow
Sorting a dict by its values
Videos
If I have a dictionary:
dict = {
"john":6,
"jill":0,
"jack":4,
"joe":2,
"jane":3
}How would I sort the keys by their values, so I would end up with something like this?
print dict
{'john': 6, 'jack': 4, 'jane': 3, 'joe': 2, 'jill': 0}
I'm familiar with the sorted() method, but that only prints the keys and even then in the ascending order. While I can live with ascending order, descending would be much better - and I certainly need the values.
I'm making a program that calculates votes for people, so after sorting the keys I will then make a for loop which prints them into a more readable format, but I'm fairly certain I can do that part - just adding this info in case it's relevant.
Thanks!
Python 3.7+ or CPython 3.6
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
or
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Older Python
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.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed we can use
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use collections.OrderedDict:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
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:
from collections import defaultdict
d = defaultdict(int)
for w in text.split():
d[w] += 1
then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key.
for w in sorted(d, key=d.get, reverse=True):
print(w, d[w])
or, if we want a dictionary back (since Python 3.6+ preserves insertion order):
{w: d[w] for w in sorted(d, key=d.get, reverse=True)}
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.