How to pass a Dict to a function with Keyword arguments?

Viewed 191

Let's assume I have this Dict:

d=Dict("arg1"=>10,"arg2"=>20)

and a function like this:

function foo(;arg1,arg2,arg3,arg4,arg5)
  #Do something
end

How can I call the function and pass the parameters in the Dict d as parameters for the function? I know I can do this:

foo(arg1=d["arg1"],arg2=d["arg2"])

But is there any way to automate this? I mean a way to figure out which arguments are defined in the Dict and pass it automatically to the function.

1 Answers

Dictionaries with Symbol keys can be directly splatted into the function call:

julia> d = Dict(:arg1 => 10, :arg2 => 12)
Dict{Symbol, Int64} with 2 entries:
  :arg1 => 10
  :arg2 => 12

julia> f(; arg1, arg2) = arg1 + arg2
f (generic function with 1 method)

julia> f(; d...)
22

Note the semicolon in the function call, which ensure that the elements in d are interpreted as keyword arguments instead of positional arguments which just happen to be Pairs.

Related