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?
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)
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)
From CPython 3.6:
{'a': 1, 'b': 3, 'c': 2}
{'a': 1, 'c': 2, 'b': 3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With