Appending to a dictionary in Julia

I recently completed the course Introduction to Julia (for programmers). However, in the lecture titled Data Structures, there was a part where it was shown how to add an entry to a dictionary. Now suppose we have a dictionary like the following:

myphonebook = Dict("Jenny" => "867-5309", "Ghostbusters" => "555-2368")

and suppose we want to add one more entry and thus, we may write it as:

myphonebook["Kramer"] = "555-FILK"

I expected the modified dictionary to be like this:

Dict{String, String} with 3 entries:
  "Jenny"        => "867-5309"
  "Ghostbusters" => "555-2368"
  "Kramer"       => "555-FILK"

However, in both, the lecture and on my computer, after I did the above operation, I found that my newly added element was augmented in between the last two elements:

Dict{String, String} with 3 entries:
  "Jenny"        => "867-5309"
  "Kramer"       => "555-FILK"
  "Ghostbusters" => "555-2368"

I would like to know why Julia is adding my entry at another location instead of just “appending” my entry at the very end.

P.S. This question might be similar to the one asked here.

1 Like

take a look here

“… Because dictionaries don’t store the keys in any particular order, you might want to output the dictionary to a sorted array to obtain the items in order: …”

or try using Dictionaries

using Dictionaries

mphb = Dictionary("Jenny" => "867-5309", "Ghostbusters" => "555-2368")

julia> mphb = Dictionary("Jenny" => "867-5309", "Ghostbusters" => "555-2368")
2-element Dictionary{String, String}
    "Jenny" │ "Ghostbusters"
 "867-5309" │ "555-2368"

insert!(mphb,"Kramer", "555-FILK")

julia> mphb
3-element Dictionary{String, String}
    "Jenny" │ "Ghostbusters"
 "867-5309" │ "555-2368"
   "Kramer" │ "555-FILK"

3 Likes

A Dict is an unordered collection; the order the entries are printed in does not have a particular meaning. “Appending” does not really make sense in that context.

2 Likes

if you need dictionaries that preserve insertion order, you can use OrderedDict from OrderedCollections.jl

2 Likes