Sorting a list based on the 2nd element of a tuple

I have a dictionary and you want to convert it to a list. Then I would like to sort the resulting list, consisting of pairs {Key, Value} from min to max, depending on the second element (Value).

Is there a built-in sorting method for lists to handle this, or how to do it?

thanks

+4
source share
2 answers

The easiest way to sort by the second element is to define your own sort function, which could work as follows:

fun({KeyA,ValA}, {KeyB,ValB}) -> {ValA,KeyA} =< {ValB,KeyB} end. 

And name it in lists:sort/2 :

 1> lists:sort(fun({KeyA,ValA}, {KeyB,ValB}) -> {ValA,KeyA} =< {ValB,KeyB} end., [{a,b},{b,a},{b,b}]). [{b,a},{a,b},{b,b}] 

This is because Erlang will always automatically compare tuples from the first to the last element. This function changes the first and second elements so that the second acts as the first comparison point. Then the key in your dict will be used to order records where the values ​​are the same.

+6
source

The lists: keysort / 2 function is suitable as a glove for this.

1> lists:keysort(2, [{a,b},{b,a},{b,b}]).

[{b,a},{a,b},{b,b}]

2> lists:keysort(2, [{1,14},{3,10},{2,13}]).

[{3,10},{2,13},{1,14}]

+10
source

All Articles