Narrowing types on a Dict

Suppose I am accumulating key-value pairs of a previously unknown type in a Dict{Any,Any} within a function. But before I return the result, I would like to narrow the type parameters as much as possible.

Is there some compact syntax for that? I came up with

Dict(Base.Generator(identity, dict))

but it looks like a kludge.

You can do the following for example:

julia> d = Dict()
Dict{Any,Any} with 0 entries

julia> d[3] = "hello"; d[4] = "goodbye"
"goodbye"

julia> d
Dict{Any,Any} with 2 entries:
  4 => "goodbye"
  3 => "hello"

julia> Dict(Pair(kv) for kv in d)   # kv are key-value pairs
Dict{Int64,String} with 2 entries:
  4 => "goodbye"
  3 => "hello"
1 Like

Nice. With the definitions of your example, Dict(kv for kv in d) seems to work too.

3 Likes

Not quite sure why that works but Dict(d...) doesn’t.