Home > Software engineering >  How to pass a Dict to a function with Keyword arguments?
How to pass a Dict to a function with Keyword arguments?

Time:10-20

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.

CodePudding user response:

For dictionaries with Symbol keys you can splat them 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
  • Related