Sort Dict by Values in Python 3.6+
Asked Answered
M

5

12

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?

Moppet answered 2/9, 2018 at 23:45 Comment(2)
Possible duplicate of How can I sort a dictionary by key?Tragedy
@newbie, not sure how a question that sorts by key is a dupe for one asking for sort by value?Jepson
R
4

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)
Roach answered 17/8, 2021 at 4:40 Comment(0)
J
19

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, and guaranteed in all python implementations 3.7+:

{'a': 1, 'b': 3, 'c': 2}
{'a': 1, 'c': 2, 'b': 3}
Jepson answered 2/9, 2018 at 23:49 Comment(4)
In what way will this sort the dictionary?Historiography
@PeterWood, In CPython 3.6 and Python 3.7+ Dicts are ordered.Jepson
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 documentationTragedy
@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.Jepson
R
4

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)
Roach answered 17/8, 2021 at 4:40 Comment(0)
S
1

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

sorted_list_by_value=sorted(data_dict, key=data_dict.__getitem__)
Scrambler answered 23/11, 2019 at 16:13 Comment(0)
W
0

Similar to the top answer but without the dict comprehension, resulting in marginally faster and shorter code:

Code:

dict(sorted(a.items(), key=lambda x: x[1]))

sorted returns a list of tuples, which dict() then uses as its key/value pairs.

Example:

a = {'a': 1, 'b': 3, 'c': 2}
a = dict(sorted(a.items(), key=lambda x: x[1]))
print(a)

Results:

{'a': 1, 'c': 2, 'b': 3}

Works in CPython 3.6+ and all Pythons 3.7+.

Wrapper answered 11/1 at 0:48 Comment(0)
B
-1

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

from collections import OrderedDict
d = {1: 1, 2:4, 5:2, 9:3}
sorted_dict = OrderedDict(sorted(d.items(),key=lambda x: x[1]))

Edited to include sort into sorted dict

Blackleg answered 3/9, 2018 at 3:1 Comment(2)
OrderedDict preserves the order in which the keys are inserted and does not store them in increasing or decreasing order by value.Keyser
In old version of python dicts were explicitly unordered so if you wanted to sort a dict you'd need to do something like OrderedDict(sorted(d,key=lambda x:d[x])) the accepted answer isn't a "sorted dict" it's a sorted iterable of tuplesBlackleg

© 2022 - 2024 — McMap. All rights reserved.