Search code examples
dictionaryvectorsyntaxinitializationjulia

How to initialize a dictionary in Julia?


When I tried to do:

d = {1:2, 3:10, 6:300, 2:1, 4:5}

I get the error:

syntax: { } vector syntax is discontinued

How to initialize a dictionary in Julia?


Solution

  • The {} syntax has been deprecated in julia for a while now. The way to construct a dict now is:

    Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.

    julia> Dict([("A", 1), ("B", 2)])
      Dict{String,Int64} with 2 entries:
        "B" => 2
        "A" => 1
    

    Alternatively, a sequence of pair arguments may be passed.

    julia> Dict("A"=>1, "B"=>2)
      Dict{String,Int64} with 2 entries:
        "B" => 2
        "A" => 1
    

    (as quoted from the documentation, which can be obtained by pressing ? in the terminal to access the "help" mode, and then type Dict)