Loop in dictionary definition

Hello,
I’m using a library that uses a dictionary to set variables along points, like so:

bla = Dict(
    1 => foo,
    2 => bar
)

I want to create that dictionary over a large number of points and that number is not constant. Something like:

bla = Dict(
    for i in 1:N
        i => foo[i],
    end
)

How can I achieve this?
Thanks a lot!

You can use a comprehension for this::

julia> N = 5;

julia> foo = rand(N);

julia> bla = Dict(i => foo[i] for i in 1:N)
Dict{Int64, Float64} with 5 entries:
  5 => 0.825488
  4 => 0.308265
  2 => 0.932313
  3 => 0.495245
  1 => 0.490559
1 Like

Oh, that’s great, thanks!
How do I combine that with a defined entry? I never worked with Dictionaries before. Can I add a new point (say point 6) after bla = Dict(i => foo[i] for i in 1:N)?
Something like:

bla = Dict(i => foo[i] for i in 1:N, 6=>0.2)

Thanks!

Just figured out the merge command. So if that’s the way to go, I’m happy. Thanks again!

Yup, merge will certainly work. On the other hand, you might also consider just using a loop–loops are fast in Julia, and often the easiest way to do things:

julia> d = Dict{Int, Float64}()
Dict{Int64, Float64}()

julia> for i in 1:N
         d[i] = foo[i]
       end

julia> d[6] = 0.2
0.2

julia> d
Dict{Int64, Float64} with 6 entries:
  5 => 0.825488
  4 => 0.308265
  6 => 0.2
  2 => 0.932313
  3 => 0.495245
  1 => 0.490559

Ah, that is also a neat way to do it. Thanks!