Initialize Dict to enable values of different type

What is the reason that case 3 fails? And how to avoid this?
How can I initialize a Dict to enable values of different type?
Here is my snippet:


function MyDictFill(_a::Dict = Dict())
    if ~haskey(_a, "a")
        _a["a"] = true
    end
    if ~haskey(_a, "b")
        _a["b"] = 1.0
    end
    if ~haskey(_a, "c")
        _a["c"] = "str"
    end
    return _a
end

# case 1: ok
MyDictFill()

# case 2: ok
begin
    dict_a = Dict()
    dict_a["d"] = "star"
    dict_a["e"] = 1
    dict_a["f"] = true
    MyDictFill(dict_a)
end

# case 3: fails
begin
    dict_b = Dict()
    dict_b = Dict("d" => 2)
    dict_b = Dict("f" => "julia")
    MyDictFill(dict_b)
end

What behaviour do you expect exactly?

The third case fails because you define dict_b 3 times.
The last call gives you

julia> dict_b = Dict("f" => "julia")
Dict{String, String} with 1 entry:
  "f" => "julia"

If you fill a Dict{String, String} with non-string values, you will get a MethodError.

You could initialize the Dict with value type Any instead.

julia> dict_b = Dict{String,Any}("f" => "julia")
Dict{String, Any} with 1 entry:
  "f" => "julia"

julia> MyDictFill(dict_b)
Dict{String, Any} with 4 entries:
  "f" => "julia"
  "c" => "str"
  "b" => 1.0
  "a" => true
3 Likes

Thanks, now I see my mistake. Thanks a lot! :slight_smile:

Here some other examples of Dict initialization:

dict_b = Dict{String, Union{Nothing, String, Bool, Number}}("a" => "Julia", "b" => true, "c" => 10.0, "n" => nothing)
isnothing(dict_b["n"])

dict_c = Dict{Bool, String}(true => "Julia", false => "Romeo")
dict_c[true]

dict_d = Dict{Int, String}(1 => "one", 2 => "two", 3 => "three")
dict_d[1]
for (_k, _v) in dict_d
   println("#", _k, ": ", _v)
end
for _i = 1:length(dict_d) # eachindex() does not work here
   println("#", _i, ": ", dict_d[_i])
end