Julia how to create a dictionary using a loop

Hi there,

I am new to Julia and I need a little help with the abovementioned task. I want to create a list of dictionary with tuples as keys and a real number as values. Below is the piece of code a wrote, but the result I get,
(5, 5)=>3.0e-5
,seem to only show the last (key, value) pair.

v = 5
w=[]
for i=1:v
	for j=1:v
		if i != j
			w=(i,j) => 0.00001
		else
			w=(i,j) => 0.00003
		end
	end
end
println("w \n :----->  ", w)

What I was really expecting are the following:

# expected outcome:
[(1,1) => 0.00003, (1,2)=> 0.0001, (1,3) => 0.00001, (1,4) => 0.00001, (1,5) => 0.00001,
(2,1) => 0.00001, (2,2) => 0.00003, (2,3) => 0.00001, (2,4) => 0.00001, .... , (5,5) => 0.00003]

Thanks in advance for your help.

This works:

julia> v = 5
       w = Dict()
       for i=1:v
           for j=1:v
               if i != j
                   w[(i,j)] = 0.00001
               else
                   w[(i,j)] = 0.00003
               end
           end
       end
       w
Dict{Any,Any} with 25 entries:
[...]

Alternatively,

julia> v = 5
       w = Dict(
           (i,j) => if i != j
               0.00001
           else 
               0.00003 
           end 
           for i = 1:v, j = 1:v
       )
Dict{Tuple{Int64,Int64},Float64} with 25 entries:
[...]

One advantage of the latter is that you get a dictionary with concrete types (Dict{Tuple{Int64,Int64},Float64}) rather than Dict{Any,Any}. Concrete types are much more performant.

2 Likes
v = 5
w = Pair{Tuple{Int64,Int64},Float64}[]
for i=1:v , j=1:v
		push!( w ,  (i,j) =>  i != j ? 0.00001 : 0.00003  )
end
println("w \n :----->  ", w)

Assuming that you wanted a list of pairs (rather than an actual dictionary)

1 Like

Thanks a bunch! Your answer is very concise.