Cannot assign struct as a dictionary value

Hi!
I have a simple struct to store some data:

struct Gene
    name::String
    exonarray::Array
    pi::Int64
    pf::Int64
    is_reverse::Bool
    #note::String 
end

I then get some data from a file and generate an object:

myname = "Gene_1"
myarray = []
mypi = 1
mypf = 1500
myrev = false

mygene = Gene(myname,myarray,mypi,mypf,myrev)

Then, I want to push this new object into a dictionary, using a string as key.

mydict = Dict
mydict[myname] = mygene

This raises an error:

ERROR: LoadError: MethodError: no method matching setindex!(::Type{Dict}, ::Gene, ::String)

What am I doing wrong? How do I assign a struct as a Dictionary value?

Change that to mydict = Dict().

Or even better:

mydict = Dict{String, Gene}()
6 Likes

if I try

mydict  = Dict()
#or
mydict = Dict{String,Gene}()

I get a slightly different error:

ERROR: LoadError: MethodError: no method matching getindex(::Gene, ::Int64)

What code are you running to get this error? The code you posted above works with either mydict = Dict() or mydict = Dict{String,Gene}():

julia> struct Gene
           name::String
           exonarray::Array
           pi::Int64
           pf::Int64
           is_reverse::Bool
           #note::String
       end

julia> myname = "Gene_1"
"Gene_1"

julia> myarray = []
Any[]

julia> mypi = 1
1

julia> mypf = 1500
1500

julia> myrev = false
false

julia> mygene = Gene(myname,myarray,mypi,mypf,myrev)
Gene("Gene_1", Any[], 1, 1500, false)

julia> mydict = Dict{String,Gene}()
Dict{String,Gene}()

julia> mydict[myname] = mygene
Gene("Gene_1", Any[], 1, 1500, false)

julia> mydict
Dict{String,Gene} with 1 entry:
  "Gene_1" => Gene("Gene_1", Any[], 1, 1500, false)
1 Like

Big confusion. I modified the variable names a bit, (like my_dict to mydict, and my_gene to mygene).
Now the code works as it should. Thanks for your help!
What is the effect of the ()? What is the difference between Dict and Dict()?

Dict is a type and Dict() creates an object of that type (in this case, of the type Dict{Any,Any}, which is a concrete subtype of Dict). It’s like the difference between Int64 (a type) and 5 (a value of that type).

3 Likes

For better performance, you should pick a concrete type for the exonarray field, like Array{Int64,1} instead of Array.

2 Likes