ErcAnd17
ErcAnd17

Reputation: 23

Julia: Writing a function "paramvalues" that returns a dictionary of parameter values

I am working on an Economics assignment and need to create a function in Julia that takes keyword arguments and returns them in the form of a dictionary. So far this is my code, but it is not running because there is "no method matching getindex(::Nothing, ::Symbol).

function paramvalues(a; Nb = 100, Ns = 100, Minval = 0, Maxval = 200, Mincost = 0, Maxcost = 200)
    d = Dict(:Nb => Nb, :Ns => Ns, :Minval => Minval, :Maxval => Maxval, :Mincost => Mincost, :Maxcost => Maxcost)
    for values in a
        d[values] = get(d, values, 0) 
    end
    d 
end

Upvotes: 2

Views: 66

Answers (2)

phyatt
phyatt

Reputation: 19102

This is probably closer to what you want:

function paramvalues(a; kwargs...)
    @show kwargs
    dict = collect(kwargs)
    @show dict
    return dict
end

The magic here is that kwargs (aka Key Word Arguments) with the ... "SLURP", soaks up all the key word arguments into one variable.

And it is an iterator over an array of pairs. To convert an iterator into a standard collection like an Array or a Dict, you can use collect. An iterator over pairs turns into a Dict.

Trying it out I get this:

paramvalues(123;Nb = 100, Ns = 100, Minval = 0, Maxval = 200, Mincost = 0, Maxcost = 200)
kwargs = Base.Iterators.Pairs(:Nb => 100,:Ns => 100,:Minval => 0,:Maxval => 200,:Mincost => 0,:Maxcost => 200)
dict = Pair{Symbol,Int64}[:Nb => 100, :Ns => 100, :Minval => 0, :Maxval => 200, :Mincost => 0, :Maxcost => 200]
6-element Array{Pair{Symbol,Int64},1}:
      :Nb => 100
      :Ns => 100
  :Minval => 0
  :Maxval => 200
 :Mincost => 0
 :Maxcost => 200

I don't know what a is supposed to be.

It sounds like your error is coming from calling get on a variable storing Nothing instead of storing a Dict.

Also when walking a dictionary, it returns a tuple pair of (key, value). So use something like this to walk a dictionary:

for (k,v) in my_dict
    @show k,v
end

Also don't forget to use the ? in the julia repl and search some of these things. Like ?Dict or ?for or ?enumerate or ?@show or ?collect.

Upvotes: 1

MarcMush
MarcMush

Reputation: 1488

Dict can directly take the keyword-arguments:

julia> f(;kw...) = Dict(kw)
f (generic function with 1 method)

julia> f(a=5, b=3)
Dict{Symbol, Int64} with 2 entries:
  :a => 5
  :b => 3

Upvotes: 2

Related Questions