Cannot reassign dict entry with nothing value

I just started coding in Julia today, and I have a slight problem with Dict(), when I create one that has only “nothing” or “missing” as values, I cannot later reassign the values to something else:

In: noth_dict = Dict(“A” => nothing)
Out: Dict{String,Nothing} with 1 entry:
“A” => nothing

In: noth_dict[“A”] = 1
Out: MethodError: convert(::Type{Union{}}, ::Int64) is ambiguous. Candidates:
convert(::Type{Union{}}, x) in Base at essentials.jl:166
convert(::Type{T}, x::Number) where T<:Number in Base at number.jl:7
convert(::Type{T}, arg) where T<:VecElement in Base at baseext.jl:8
convert(::Type{T}, x::Number) where T<:AbstractChar in Base at char.jl:179
Possible fix, define
convert(::Type{Union{}}, ::Number)

Stacktrace:
[1] convert(::Type{Nothing}, ::Int64) at ./some.jl:34
[2] setindex!(::Dict{String,Nothing}, ::Int64, ::String) at ./dict.jl:380
[3] top-level scope at In[210]:1

I would appreciate any help with this.

Your dictionary can only hold keys of type String and values of type Nothing, as indicated in the output; it is a dictionary of type Dict{String,Nothing}. If you want your dictionary to accept, for example, both nothing and integers as values you can specify that when constructing the dictionary:

julia> dict = Dict{String,Union{Nothing,Int}}("A" => nothing)
Dict{String,Union{Nothing, Int64}} with 1 entry:
  "A" => nothing

julia> dict["A"] = 1
1

See also PSA: how to quote code with backticks for how to post code-formatted code (which makes it easier to read).

3 Likes

Thank you very much for the quick response! Now it makes sense, I was treating the Dict like a Python one. I suppose the type specifications is to allow for some optimisation. I will follow the post guidelines :slight_smile:

I believe a python dict would be equivalent to Dict{Any,Any} in Julia, i.e. it can hold any type of keys and values.