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

dictionary

#1

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


#2

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


#3

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

#4

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?


#5

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


#6

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