# Is there a many to one dictionary shorthand?

Consider this named tuple, which could also be written as a dictionary
(a = 1, b = 1, c = 2, d = 2)

Is there a shorthand to group keys with the same value eg?
( (a,b) = 1, (c,d) = 2)

Could use an if - in statement. Just wondering if there’s a nice shorthand like above

I have been known to do:

``````julia> Dict([[:a, :b] .=> 1; [:c, :d] .=> 2])
Dict{Symbol, Int64} with 4 entries:
:a => 1
:b => 1
:d => 2
:c => 2
``````

though this is not particularly efficent. (probably find if you are working so few elements you are writing literals)

How this works:
`.=>` is broadcasted `Pair`

``````julia> x = [:a, :b] .=> 1
2-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 1

julia> y = [:c, :d] .=> 2
2-element Vector{Pair{Symbol, Int64}}:
:c => 2
:d => 2
``````

`;` insde `[]` is `vcat`

``````julia> [x; y]
4-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 1
:c => 2
:d => 2
``````

And then `Dict` can be constructed from a `Vector{<:Pair}`

9 Likes

Thanks Lyndon
That’s really cool. I see you can also do it with spaces and newlines instead of , and ;

``````Dict([
[:a  :b]  .=> 1
[:c  :d]  .=> 2
])
``````

This has nothing to do with `Dict` or `Pair` but pertains to how an array (particularly a matrix) is built in Julia.

1. `[:a :b]` is a row vector, and `[:a :b] .=> 1` produces also a row vector by broadcasting.
``````julia> [:a  :b]  .=> 1
1×2 Array{Pair{Symbol,Int64},2}:
:a=>1  :b=>1
``````
1. The newlines inside a `[ ]` works like `vcat`. In the above example, it means to concatenate two 1x2 vectors vertically into a 2x2 matrix.
``````julia> [[1 2]
[3 4]
]
2×2 Array{Int64,2}:
1  2
3  4

julia> [
[:a  :b]  .=> 1
[:c  :d]  .=> 2
]
2×2 Array{Pair{Symbol,Int64},2}:
:a=>1  :b=>1
:c=>2  :d=>2
``````
1. Since the resultant 2x2 matrix is iterable, the constructor `Dict([itr])` is called.

Note that `[1, 2]` is a column vector while `[1 2]` is a row vector. The `;` is equivalent to a newline when building a matrix (also equal to `vcat`; if you want to write them in a single line).

``````julia> [[1, 2]; [2, 3]]
4-element Array{Int64,1}:
1
2
2
3

julia> vcat([1, 2], [3, 4])
4-element Array{Int64,1}:
1
2
3
4
``````

while the space between elements defines a row, or more generally, horizontal concatenation.

``````julia> [[1, 2] [3, 4]]
2×2 Array{Int64,2}:
1  3
2  4

julia> hcat([1, 2], [3, 4])
2×2 Array{Int64,2}:
1  3
2  4
julia> [1 3; 2 4]
2×2 Array{Int64,2}:
1  3
2  4
``````
4 Likes

Thanks Shuhua. very useful