11

I was looking for a method to sort a dictionary in Python with its values, after a few attempts, is what it comes:

a = {<populated dict...>}
a = {v: k for k, v in a.items()}
a = {v: k for k, v in sorted(a.items())}

This code seems to work, but I think it's poor for performance, is there a better way?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Giuseppe
  • 531
  • 1
  • 5
  • 19
  • 1
    Possible duplicate of [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – abc Sep 02 '18 at 23:54
  • 5
    @newbie, not sure how a question that sorts by key is a dupe for one asking for sort by value? – Stephen Rauch Sep 02 '18 at 23:56

4 Answers4

18

You do not need to do the double key/value swap, you can do this:

a = {k: v for k, v in sorted(a.items(), key=lambda x: x[1])}

(sorted DOCS)

Test Code:

data = dict(a=1, b=3, c=2)
print(data)
data_sorted = {k: v for k, v in sorted(data.items(), key=lambda x: x[1])}
print(data_sorted)

Results:

From CPython 3.6:

{'a': 1, 'b': 3, 'c': 2}
{'a': 1, 'c': 2, 'b': 3}
Community
  • 1
  • 1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • In what way will this sort the dictionary? – Peter Wood Sep 02 '18 at 23:58
  • @PeterWood, In CPython 3.6 and Python 3.7+ Dicts are ordered. – Stephen Rauch Sep 02 '18 at 23:59
  • 1
    I don't like it as an approach. Insertion sort is a feature since 3.6 but `The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon` from the [documentation](https://docs.python.org/3/whatsnew/3.6.html) – abc Sep 03 '18 at 00:09
  • 3
    @newbie, your are technically correct. However, for 99% of the world, CPython is Python. And for this feature at least, in 3.7 it is no longer an implementation detail. – Stephen Rauch Sep 03 '18 at 00:10
3

By default, the dictionary is sorted based on keys, but the sorted function takes a function as a parameter using which you can alter the behaviour for program.

d={'a':6,'b':4,'k':3}
print(sorted(d)) 

sorted_by_values= sorted(d,key=lambda x:d[x])
print(sorted_by_values)
thinkingmonster
  • 5,063
  • 8
  • 35
  • 57
1

The following code works for me. Not sure how efficient is this.

sorted_list_by_value=sorted(data_dict, key=data_dict.__getitem__)
0
from collections import OrderedDict

otherwise create a list of keys in the order you want.

Schalton
  • 2,867
  • 2
  • 32
  • 44