isebarn
isebarn

Reputation: 3940

Julia - using dictionary key as index for a multidimensional array

I have a dictionary with keys as shown:

testdict = Dict{Array{Int64,1},Float64}([1,3,1] => 0.0, [2,3,1] => 0.0, [1,3,2] => 0.0, [2,3,2] => -2.64899e-16, [2,1,2] => 0.858307, [1,2,1] => 0.0, [1,2,2] => 0.0, [2,2,1] => 0.0, [2,2,2] => 0.65796, [2,1,1] => -5.81556e-16, [1,1,2] => -3.50541e-16, [1,1,1] => 0.0)

These keys vary considerably both regarding range and length, they are initialized by an array in the beginning of the function Im writing...it could look like

[2,3,2]

for the dictionary above...,

or

[10,3,50,60]

creating a dictionary with keys

[1,1,1,1], [1,1,1,12] ... , [10, 3, 50, 59], [10,3, 50, 60]

And what I need to accomplish, is create a multidimensional array by

result_array = Array(Float64, tuple([2,3,2])

But then I need to populate the array with the values from the dictionary, so I would need to set element [1,1,1] as

result_array[1,1,1] = 0.0

How can I use the keys from the dictionary to set the indices of the result_array with their respected values?

Upvotes: 2

Views: 2045

Answers (1)

Chris Rackauckas
Chris Rackauckas

Reputation: 19132

Splat the key to turn result_array[[1,1,1]...] into result_array[1,1,1].

testdict = Dict{Array{Int64,1},Float64}([1,3,1] => 0.0, [2,3,1] => 0.0, [1,3,2] => 0.0, [2,3,2] => -2.64899e-16, [2,1,2] => 0.858307, [1,2,1] => 0.0, [1,2,2] => 0.0, [2,2,1] => 0.0, [2,2,2] => 0.65796, [2,1,1] => -5.81556e-16, [1,1,2] => -3.50541e-16, [1,1,1] => 0.0)

result_array = Array(Float64,2,3,2)

for (k,v) in testdict
  result_array[k...] = testdict[k]
end

Upvotes: 4

Related Questions