# CICLE FOR and DICTIONARY

I have to write a FOR’s cicle from 1 to 100 and then I have to create a “Dict” ,Called squares, which contains as key the int number and as elements their squares.

I have written

For i in 1:100
Squares=Dict(i=>i^2)
End

But it doesn’t run.
Can someone help me?

You’re close:

``````julia> squares = Dict()    # but Dict{Int,Int}() is better when you need performance
Dict{Any,Any} with 0 entries

julia> for i=1:100
squares[i] = i^2
end

julia> squares
Dict{Any,Any} with 100 entries:
68 => 4624
2  => 4
89 => 7921
11 => 121
39 => 1521
46 => 2116
...
``````

Or here’s a nice one-liner:

``````julia> squares = Dict(i => i^2 for i in 1:100)
Dict{Int64,Int64} with 100 entries:
68 => 4624
2  => 4
89 => 7921
11 => 121
39 => 1521
46 => 2116
...
``````

Note that elements are stored in indeterminate order in a `Dict`.

The code you wrote didn’t work because you assign a new `Dict` in each iteration of the loop. You should also avoid capitalizing keywords, but maybe that was just in your post.

3 Likes

Thank you very much!