Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Dict by Values in Python 3.6+

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?

like image 590
Giuseppe Avatar asked Sep 02 '18 23:09

Giuseppe


1 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}
like image 149
Stephen Rauch Avatar answered Oct 14 '22 15:10

Stephen Rauch