How to initialize a dictionary in Julia?
Asked Answered
B

2

8

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?

Bryanbryana answered 7/2, 2017 at 9:50 Comment(5)
@ajcr there was a very similar syntax in the early versions (i.e. before 0.4), but admittedly with => instead of : (i.e. d = {1=>2, 3=>10}). But yes, this is now deprecated.Colorless
Ah, I wasn't aware of that syntax in earlier versions - thanks for pointing that out.Pettifog
"How to initialize a dictionary in Julia?" is too broad? C'mon, folks. This is a well-defined question with a well-defined answer. There's no need to close this question.Neurasthenia
I initially voted to close thinking that approaches to initialisation might vary given the data you're creating the Dict from, etc., and this context wasn't explicitly stated. Looking at the question again now, this decision was probably too harsh since the OP gave a code example and it's clear how this should be changed. For what it's worth, I've voted to reopen the question (even though there is a good answer below).Pettifog
I don't believe the close reason is valid. This question, although it could be edited, is useful for a Q/A site.Encaustic
C
22

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)

Colorless answered 7/2, 2017 at 13:16 Comment(0)
D
0

If you want to create an empty dictionary D, you can use:

D = Dict()

This will create a dictionary whose keys and values have type Any. If you want to create a dictionary in which keys must be of type String and values must be of type Int, you can use:

D = Dict{String, Int}()

You can then add new key-value pairs:

D["a"] = 1
D["b"] = 2

You can of course directly do:

D = Dict{String, Int}("a" => 1, "b" => 2)

You can always add new key-value pairs later if you want.

Dvandva answered 11/4, 2023 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.