Dictionary comprehension with interdependent variables

I want to build a dictionary that corresponds to an lower triangular array (i.e., a[i,j] only exists if i>j). How can I write a dictionary comprehension that achieves this?

I tried

Dict( (i,j) => f(i,j) for j in i+1:N, i in 1:N )

and

Dict( (i,j) => f(i,j) for i in 1:N, j in i+1:N )

but they both fail with the same error:

ERROR: UndefVarError: i not defined
Stacktrace:
 [1] top-level scope at none:0
1 Like
julia> f(i, j) = i + j
f (generic function with 1 method)

julia> N = 4
4

julia> Dict( (i,j) => f(i,j) for i in 1:N for j in i+1:N )
Dict{Tuple{Int64,Int64},Int64} with 6 entries:
  (1, 2) => 3
  (2, 3) => 5
  (1, 4) => 5
  (2, 4) => 6
  (1, 3) => 4
  (3, 4) => 7

maybe?

3 Likes

Thanks!