I am trying to pass a Dict to a function in Julia. The Dict contains pairs of argument names and their respective values. Let’s say I have a function f and a Dict d:
julia> function f(x=10, y=10, z=10); return x^2, y^2, z^2; end julia> d = Dict("x"=>3, "z"=>7, "y"=>5)
This throws a MethodError:
julia> f(d...) ERROR: MethodError: no method matching ^(::Pair{String,Int64}, ::Int64)
I also tried using a NamedTuple, but this seems useless as it is sensitive to the order of the elements in the tuple and doesn’t match their names with the function argument names:
julia> t = (x=3, z=7, y=5) julia> f(t...) (9, 49, 25)
I am sure there is a way to do this. Am trying to do this with the wrong types? In python, what I am looking for would look like this:
>>> def f(x=10, y=10, z=10): ... return x**2, y**2, z**2 >>> d = {'x':3, 'z':7, 'y':5} >>> f(**d) (9, 25, 49)
Advertisement
Answer
Firstly, since you want the names of the arguments to be important (keyword arguments) you need to use a ;
in the function definition:
f(;x=10, y=10, z=10) = x^2, y^2, z^2
Secondly, you should use a dictionary where the keys are Symbol
s:
d = Dict(:x=>3, :z=>7, :y=>5)
And thirdly, you want to indicate that you are splatting keyword arguments by splatting after ;
:
f(;d...) # giving the result (9, 25, 49)