Using custom types in OrderedDict

#1

I am writing a code that reads a binary file and populates an OrderedDict. I have custom types that i made such as:

mutable struct WBGAIN
	R::Float32
	B::Float32
end

when i try to do something like this:

using DataStructures: OrderedDict
function readheader(fname)
    h = OrderedDict()


        fhtypes = OrderedDict(          # File header
            :HeadSize       => UInt16,
            :Compression    => UInt16,
            :Version        => UInt16,
            :WBgain1 => WBGAIN)
end

I get an error saying that the type WBGAIN is not supported by OrderedDict. Is there a way to put custom types into an OrderedDict?

#2

I’m not able to reproduce this error, could you show the stack trace of the error explicitly?

#3

There is a distinction between the types of dictionary values and valuing dictionary keys.
Initialize your dictionary with typed values rather than types:

using DataStructures: OrderedDict

mutable struct MyStruct
    value1::Float32
    value2::Float32
end

myodict = OrderedDict( :HeadSize => UInt16(1), 
                       :MyStruct => MyStruct(0.0f0, 0.0f0) )

# OrderedDict{Symbol,Any} with 2 entries:
#  :HeadSize => 0x0001
#  :MyStruct => MyStruct(0.0, 0.0)

myodict[:MyStruct] = MyStruct(1.0f0, 2.0f0)
# MyStruct(1.0f0, 2.0f0)

myodict
# OrderedDict{Symbol,Any} with 2 entries:
#   :HeadSize => 0x0001
#  :MyStruct => MyStruct(1.0, 2.0)