Dictionary Initialization and Usage

I started with Julia today and was experimenting with Dictionary feature. The following is the code I wrote when I faced the error. Could anyone point out as to why such error is occuring and why such usage is wrong?

Any help would be appreciated!

Maybe Julia thinks it is inconceivable that Freiburg is third??

The actual answer is:

julia> x = Dict{String, Int64}
Dict{String, Int64}

julia> typeof(x) # x is not a Dict!

you have not instantiated a Dictionary, but rather assigned the value Dict{String, Int64}, which is a type, to the binding bundesliga_table_position.

The error is telling you that you cannot add an entry to a DataType. To instantiate an object of a type, use parentheses:

julia> x = Dict{String, Int64}()
Dict{String, Int64}()

julia> typeof(x) # x is a Dict now!
Dict{String, Int64}

julia> x["a"] = 1

julia> x
Dict{String, Int64} with 1 entry:
  "a" => 1

Although inconceivable for sure :wink: your answer is spot on. I didn’t think this was even possible!
Thank you for your crisp and prompt answer. Thanks for the help!

No problem. One additional complication that I missed is that your first line also made bundesliga_table_position and alias for Dict{String, Int64} which can therefore be used to construct a dictionary. So you’ve essentially created a less flexible Dict constructor:

julia> my_alias = Dict{String, Int64}
Dict{String, Int64}

julia> Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
  "b" => 2
  "a" => 1

julia> my_alias("a" => 1, "b" => 2) # my_alias can now create new Dicts
Dict{String, Int64} with 2 entries:
  "b" => 2
  "a" => 1

julia> my_alias("a" => "b", "b" => "c") # But only String => Int Dicts
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64

julia> Dict("a" => "b", "b" => "c") # Unlike the actual Dict constructor
Dict{String, String} with 2 entries:
  "b" => "c"
  "a" => "b"
1 Like

Ohh yes. That makes sense. :+1: