SORT a Dictionary by Numerical Keys

I have a Dictionary:

A = Dict("1"  => 0.1,
  "11" => 0.1,
  "13" => 0.1,
  "15" => 0.1,
  "17" => 0.1,
  "19" => 0.1,
  "3"  => 0.1,
  "5"  => 0.1,
  "7"  => 0.1,
  "9"  => 0.1)

I want to sort it according to its numerical keys. I tried this:

sort(A)

But it comes out as:

OrderedCollections.OrderedDict{String, Float64} with 10 entries:
  "1"  => 0.1
  "11" => 0.1
  "13" => 0.1
  "15" => 0.1
  "17" => 0.1
  "19" => 0.1
  "3"  => 0.1
  "5"  => 0.1
  "7"  => 0.1
  "9"  => 0.1

But I want:

OrderedCollections.OrderedDict{String, Float64} with 10 entries:
  "1"  => 0.1
  "3"  => 0.1
  "5"  => 0.1
  "7"  => 0.1
  "9"  => 0.1
  "11" => 0.1
  "13" => 0.1
  "15" => 0.1
  "17" => 0.1
  "19" => 0.1

How do I do this?

The problem is those aren’t numerical keys, they are strings. And the string “11” comes before the string “3” (etc.)

It seems in this case it makes more sense to have actual numbers as the keys, which would make this work exactly as you expected. If you can’t do that for whatever reason, you can also pass in a function to sort by:

sort(A, by = x -> parse(Int, x))
4 Likes

or you might want to use "03" instead of "3".

1 Like
1 Like