Qwerty
Qwerty

Reputation: 919

How to sort a dictionary according to it's keys in Julia?

I want to sort the following dictionary in Julia in way that the key values are printed in alphabetical order of the key names.

fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8);

On executing the above code and entering fruits, I get the output as:

fruits
Dict{String,Int64} with 3 entries:
  "Pomegranates" => 4
  "Apples"       => 8
  "Mangoes"      => 5

However, I expect the following result:

Apples       => 8
Mangoes      => 5
Pomegranates => 4

Upvotes: 5

Views: 2072

Answers (2)

This is because dictionaries in Julia (Dict) are not ordered: each dictionary maintains a set of keys. The order in which one gets keys when one iterates on this set is not defined, and can vary as one inserts new entries. There are two things that one can do to ensure that one iterates on dictionary entries in a specific order.


The first method is to get the set of keys (using keys) and sort it yourself, as has been proposed in another answer:

julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8);

julia> for key in sort!(collect(keys(fruits)))
           val = fruits[key]
           println("$key => $val")
       end
Apples => 8
Mangoes => 5
Pomegranates => 4


That being said, if the order of keys is important, one might want to reflect that fact in the type system by using an ordered dictionary (OrderedDict), which is a data structure in which the order of entries is meaningful. More precisely, an OrderedDict preserves the order in which its entries have been inserted.

One can either create an OrderedDict from scratch, taking care of inserting keys in order, and the order will be preserved. Or one can create an OrderedDict from an existing Dict simply using sort, which will sort entries in ascending order of their key:

julia> using OrderedCollections

julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8);

julia> ordered_fruits = sort(fruits)
OrderedDict{String,Int64} with 3 entries:
  "Apples"       => 8
  "Mangoes"      => 5
  "Pomegranates" => 4

julia> keys(ordered_fruits)
Base.KeySet for a OrderedDict{String,Int64} with 3 entries. Keys:
  "Apples"
  "Mangoes"
  "Pomegranates"

Upvotes: 7

Qwerty
Qwerty

Reputation: 919

Try this:

fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8);
for key in sort(collect(keys(fruits)))
  println("$key => $(fruits[key])")
end

It gives this result:

Apples => 8
Mangoes => 5
Pomegranates => 4

Upvotes: 3

Related Questions