logo

How to Pass Multiple Keyword Arguments at Once Using a Dictionary in Julia 📂Julia

How to Pass Multiple Keyword Arguments at Once Using a Dictionary in Julia

Explanation

Using a dictionary and a splat operator, you can pass multiple keyword arguments to a function at once.

This technique is useful when you need to apply the same options to multiple plots. If all the plots need the same options, using the function default is straightforward. However, if even one plot needs to be drawn with a different style, using default can become inconvenient.

Code

You can create a dictionary in the Dict(:keyword=>value) format and use the splat operator when passing it to a function. Make sure to input a semicolon ; before the dictionary. The ; separates keyword arguments from regular arguments. Also, the keyword names must be entered as symbols in the :keyword format.

julia> function test(x; a=1, b=2, c=3)
           println("a+$x=$(a+x)")
           println("b+$x=$(b+x)")
           println("c+$x=$(c+x)")
       end
test (generic function with 1 method)

julia> test(10, a=1, b=2, c=3)
a+10=11
b+10=12
c+10=13

julia> options = Dict(:a=>1, :b=>2, :c=>3)
Dict{Symbol, Int64} with 3 entries:
  :a => 1
  :b => 2
  :c => 3

julia> test(10; options...)
a+10=11
b+10=12
c+10=13
julia> using Plots

julia> kwargs = Dict(:ylims => (-0.5,0.5), :lw => 4, :lc => :red)
Dict{Symbol, Any} with 3 entries:
  :ylims => (-0.5, 0.5)
  :lc    => :red
  :lw    => 4

julia> p₁ = plot(randn(20); kwargs...)

julia> p₂ = plot(randn(20); kwargs...)

julia> p₃ = plot(randn(20))

julia> plot(p₁, p₂, p₃)

Environment

  • OS: Windows11
  • Version: Julia 1.10.0, Plots v1.40.3