# Correct type in function for Dict of NTuple

I need a function which takes a Dictionary, where keys are Integer Tuples, and values are Float64 types.

I do not know in advance the length of the Tuples, so I would be tempted to use the following type in the function definition (this function is just an example):

``````function tuple_dict_fun(d:: Dict{Tuple{Vararg{Int}}, Float64})
return d
end
``````

At runtime, I will create dictionaries in the following manner: `dicto = Dict((1,2)=>2.0)`, or `dicto = Dict((1,2,3)=>2.0)` (i.e. they keys are always tuples of int, but the length of the key is not fixed or known ahead of time).

However, calling the above function with dicto will yield an error such as

``````tuple_dict_fun(dicto)

MethodError: no method matching tuple_dict_fun(::Dict{Tuple{Int64, Int64, Int64}, Float64})
Closest candidates are:
tuple_dict_fun(::Dict{Tuple{Vararg{Int64}}, Float64}) at In[1]:1

``````

The reason is because the defined `dicto` has keys of a specific type `NTuple{3, Int}`, rather than the Vararg type. How should I specify the dictionaries type in the function in such a situation? Trivially I can just use `d:: Dict` and that works, but it would be nice to have something closer to what is actually being passed.

Similarly, when I construct the dictionaries, I could also set it to match the type in the above function definition, but that seems a little silly, since each given realization does have fixed length keys that are known at runtime.

Again, I stress, the keys are always tuples of int, but I do not know ahead of time the length of the tuples, so can not put that directly in the type definition. In a given dictionary which I want to pass to the function, all keys are the same length however (e.g. all length 3 or all length 2).

Thanks!

more generally, with various length tuples of elements of type T

``````dict3 = Dict( (1,2) => 2.0,  (1,2,3) => 3.0 )

accept(x) = false
accept(d::Dict{T, Float64}) where {T<:NTuple} = true

accept(dict3) == true
``````

if you prefer the more specific

`````` julia> function fn(d:: Dict{NTuple{N,Int}, Float64}) where N
return d
end

julia> dict1 = Dict((1,2)=>2.0);
julia> dict2 = Dict((1,2,3)=>2.0);

julia> fn(dict1)
Dict{Tuple{Int64, Int64}, Float64} with 1 entry:
(1, 2) => 2.0

julia> fn(dict2)
Dict{Tuple{Int64, Int64, Int64}, Float64} with 1 entry:
(1, 2, 3) => 2.0
``````
1 Like

Thanks so much, this was exactly what I needed!!