# Dictionary comprehension with interdependent variables

**URL:** <https://discourse.julialang.org/t/dictionary-comprehension-with-interdependent-variables/29909>\
**Category:** General Usage\
**Tags:** question\
**Created:** [October 14, 2019, 5:54pm UTC](https://discourse.julialang.org/t/dictionary-comprehension-with-interdependent-variables/29909 "2019-10-14T17:54:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![marcusps](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marcusps/32/537_2.png) [@marcusps](https://discourse.julialang.org/u/marcusps)\
**Post date:** [October 14, 2019, 5:54pm UTC](https://discourse.julialang.org/t/dictionary-comprehension-with-interdependent-variables/29909/1 "2019-10-14T17:54:07Z")

</div>

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

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

```

and

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

```

but they both fail with the same error:

```julia
ERROR: UndefVarError: i not defined
Stacktrace:
 [1] top-level scope at none:0

```

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [October 14, 2019, 5:58pm UTC](https://discourse.julialang.org/t/dictionary-comprehension-with-interdependent-variables/29909/2 "2019-10-14T17:58:58Z")

</div>

```julia
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?

---

<div class="post-metadata">

**Author:** ![marcusps](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marcusps/32/537_2.png) [@marcusps](https://discourse.julialang.org/u/marcusps)\
**Post date:** [October 14, 2019, 6:00pm UTC](https://discourse.julialang.org/t/dictionary-comprehension-with-interdependent-variables/29909/3 "2019-10-14T18:00:58Z")

</div>

Thanks!
