>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get)
['c', 'a', 'b']
>>> sorted(x, key=x.get)
['c', 'a', 'b']
To sort a Python dictionary, and append tuples of the key and value into a list.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
To sort a Python dictionary, and append the keys into a tuple, and the values into a tuple.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> the_keys, the_vals = zip(*[(the_key, x[the_key])
for the_key in sorted(x, key=x.get)])
>>> the_keys
('c', 'a', 'b')
>>> the_vals
(1, 2, 3)
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> the_keys, the_vals = zip(*[(the_key, x[the_key])
for the_key in sorted(x, key=x.get)])
>>> the_keys
('c', 'a', 'b')
>>> the_vals
(1, 2, 3)
The results from the above examples are in ascending order. To sort in descending order, attach reverse=True at the end of the sorted() function.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get, reverse=True)
['b', 'a', 'c']
>>> sorted(x, key=x.get, reverse=True)
['b', 'a', 'c']