How to initialize a `Dict` with `#undef` content?

I want to initialize a Dict comprised of some #undef values. How can I do this?
I tried Dict{String, Float64}(undef, 3) but it throws the following error:

ERROR: MethodError: no method matching Dict{String, Float64}(::UndefInitializer, ::Int64)

I also tried Dict{String, Float64}(undef=>undef) but it threw the following error:

ERROR: MethodError: Cannot `convert` an object of type UndefInitializer to an object of type String
The function `convert` exists, but no method is defined for this combination of argument types.

Is it possible to initialize such a container?

There is no way to directly define a Dict{String, Float64} that contains a #undef value. But you can create an empty Dict by using Dict{String, Float64}().

Or you can create an undefined vector and string first, and then make them a Dict:

a=3 # or missing, nothing
b=string()
c=Dict{String, Float64}(b=>a)
2 Likes

It makes sense for arrays, but what would that do for dictionaries?

What do you want to use it for? Do you want to pre-allocate many slots in the dictionary so that you can incrementally add many elements to it with minimum allocations (see sizehint!)?

1 Like

No, I want it to create an initialized dictionary that doesn’t contain certain values so the user won’t be able to interpret the created Dict. Like, “oh, this doesn’t contain any valuable information”.

As far as I know #undef only exists in the context of references to mutable objects, e.g.

julia> mutable struct Foo end

julia> Ref{Foo}()
Base.RefValue{Foo}(#undef)

julia> Array{Foo}(undef, 1, 2)
1Ă—2 Matrix{Foo}:
 #undef  #undef

I.e. there’s no such thing as a #undef Float64 value.

Although not really what you asked for, LazilyInitializedFields.jl may be of interest in this context.

1 Like

I’d say that canonically a Dict “marks” absent values by not having the corresponding key. So imo there is no need to have another special marker for “absent” values.
Alternatively Julia offers missing which embodies exactly the absence of information. So you could use that to marke the absent values.

1 Like

not really what you asked for, LazilyInitializedFields.jl may be of interest in this context.

This can enormously help me in my structure designation! Thank you so much for mentioning it!