(Efficiently) construct a Dictionary from a Set

Here’s a function which converts a set to a dictionary without copying the underlying data. It unfortunately depends on internal representations of these data structures in Julia 1.7.3, so only use it as a last resort and always test it to see if it still works with any other version of Julia.

function set_to_dict(s::Set{KeyType}, ValueType, mapping_function) where {KeyType}
    d = s.dict
    new_vals = Vector{ValueType}(undef, length(d.slots))
    for i in 1:length(d.slots)
        if Base.isslotfilled(d, i)
            new_vals[i] = mapping_function(d.keys[i])
        end
    end
    Dict{KeyType, ValueType}(d.slots, d.keys, new_vals, d.ndel, d.count, d.age, d.idxfloor, d.maxprobe)
end

Here’s a simple test:

julia> s = delete!(Set([1,2,3]), 3) # important to test if the function can handle sets with deletion markers
Set{Int64} with 2 elements:
  2
  1

julia> @assert set_to_dict(s, Float64, a->a/2) == Dict([1=>1/2, 2=>2/2])

Updating the dictionary will leave the original set in a broken state since some underlying data are shared. So treat the dictionary as read-only unless it’s OK to destroy the original set.

1 Like