Create a Dict from eltype


Is there a reason why dict cannot be constructed from its element type eltype(d)=Pair{K,V} but requires to pass key and value types? The constructor for a dict from its element type is similar(d, eltype(d)).
For a vector, the round trip holds: T=eltype(Vector{T}()).


You mean that you want to do Dict{eltype(d)}()? The reason that this doesn’t work is that the thing in {...} must be the parameters of the type, and Dict is parameterized by {K,V}, the key K and value V types, not by a Pair{K,V}. You can use similar if you want to pass a Pair of types, e.g. similar(d, eltype(d)) and similar(d, Pair{Int,Int}) work.


I am trying to write the documentation for similar(dict) and that is the motivation to ask the question: similar seems to be the constructor of a dictionary from Pair.

Why can’t I construct any container from its element type? To me it makes sense to have T=eltype(Dict{T}()) in the same way as we have T=eltype(Vector{T}()).


In practice, you commonly want to write functions operating on Dict that make use of the key and value types individually, so it is much more convenient to parameterize Dict{K,V} by the key and value types individually than by Pair{K,V}. The current approach also allows you to write Dict{K} to describe a family of Dict types with the same key type K but different value types.


OK for the practical approach.