Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how Julia determines index of dictionary keys?

I confronted strange behavior in Dictionary collection in Julia. a Dictionary can be defined in Julia like this:

dictionary = Dict(1 => 77, 2 => 66, 3 => 1)

and you can access keys using keys:

> keys(dictionary)

# [output] 
KeySet for a Dict{Int64, Int64} with 3 entries. Keys:
2
3
1

# now i want to make sure Julia consider above order. so i use collect and then i will call first element of it
> collect(keys(dictionary))[1]

# [output] 
2

as you can see the order of keys in keys(dictionary) output is so strange. seems Julia doesn’t consider the order of (key=>value) in input! even it doesn’t seem to be ordered ascending or descending. How Julia does indexing for keys(dictionary) output?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


Expected Output:

> keys(dictionary)

# [output] 
KeySet for a Dict{Int64, Int64} with 3 entries. Keys:
1
2
3

> collect(keys(dictionary))[1]

# [output] 
1

I expect keys(dictionary) give me the keys in the order that I entered them in defining dictionary.

>Solution :

The key order in Dict is currently undefined (this might change in the future).

If you want order to be preserved use OrderedDict from DataStructures.jl:

julia> using DataStructures

julia> dictionary = OrderedDict(1 => 77, 2 => 66, 3 => 1)
OrderedDict{Int64, Int64} with 3 entries:
  1 => 77
  2 => 66
  3 => 1

julia> keys(dictionary)
KeySet for a OrderedDict{Int64, Int64} with 3 entries. Keys:
  1
  2
  3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading