prenc
prenc

Reputation: 151

Make SortedDict sorted by values in Julia

I am new to Julia and I've noticed it's not easy to Google for things which seem to be little more beyond elementary.

I would like to create an instance of SortedDict from DataStructures package but I want it to be sorted by values.

According to the documentation, the SortedDict takes parameter o which is some kind of comparator (order), so I guess I should create the one which does what I want.

SortedDict(o=Forward)

After some search, I've found how the Forward ordering is programmed here and I must admit it's hard to decipher for me.

I wanna have an instance of such a dict: SortedDict{String,Float64} and I want it to be sorted according to these Float64s. Example:

(
    "b" => 0.1,
    "a" => 0.2,
    "c" => 0.3
)

Could someone please tell me if this is possible and if so please indicate the solution?

Upvotes: 3

Views: 423

Answers (1)

fredrikekre
fredrikekre

Reputation: 10984

The SortedDict type does seem to support sorting by value. An alternative could be to use OrderedDict from the OrderedCollections package (it is also reexported by the DataStructures package). It is ordered by insertion order, but it does allow you to sort it by value:

julia> o = OrderedDict("a" => 0.2, "b" => 0.1, "c" => 0.3)
OrderedDict{String,Float64} with 3 entries:
  "a" => 0.2
  "b" => 0.1
  "c" => 0.3

julia> sort(o, byvalue=true)
OrderedDict{String,Float64} with 3 entries:
  "b" => 0.1
  "a" => 0.2
  "c" => 0.3

Upvotes: 1

Related Questions