Sort Dict by Values in Python 3.6+

Viewed 30538

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?

4 Answers

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}

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)

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

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

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

Related