Why `Dict("A"=>1, "B"=>2)` instead `Dict("A":1, "B":2)`?

Dear DevTeam,

I saw Julia incorporated features from both Python and Matlab and I really appreciate its performance in-terms of speed.

As a python user we love writing dictionaries as {key:value}. I appreciate if you could add this convention to Julia. I have also noticed Julia have tuple like convention for dictionaries.
Example : Dict([("A", 1), ("B", 2)]) .

Thank you

1 Like

No that’s impossible since it conflicts with existing syntax.

If you insist on that syntax, you can just write a function like

julia> tuples2dict(iter) = Dict(k => v for (k,v) in iter)
tuples2dict (generic function with 1 method)

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

One of the REALLY cool things about Julia is how you can use macros to satisfy almost any of your own personal syntax whims. So, just for fun, let’s write a simple macro for this:

macro dict(expr)
    errormessage = "Usage:  @dict key1:value1, key2:value2, ..."
    if typeof(expr) != Expr
        error(errormessage)
    elseif expr.head == :(:)
        expr = :($expr,)
    elseif expr.head != :tuple
        error(errormessage)
    end
    d = Dict()
    for colonitem in expr.args
        if typeof(colonitem) != Expr || colonitem.head != :(:)
            error(errormessage)
        end
        d[colonitem.args[1]] = colonitem.args[2]
    end
    d
end

Now you can make Dicts like this:

d = @dict "cat":3, "mouse":4, "dog":5

Neat huh?

9 Likes

Yeah, that’s cool. Thank you :sunglasses:

currently Julia is installing on my Ubuntu machine, once it is done I’ll test it out and share my experiments.