I have two dictionaries a1
and a2
in Julia.
a1 = {"A"=>1, "B"=>2}
a2 = {"A"=>4, "B"=>1, "C"=>3}
I would like to combine it to get this.
final={"A"=>5, "B"=>3, "C"=>3}
In Python, I convert the dictionary to collection counter and combine them together.
Dictionaries in Julia allow accessing all the keys and all the values at once. This can be done with the use of pre-defined keywords keys and values. All the Key-value pairs of a dictionary can be printed at once, with the use of for-loop.
A dictionary in Julia can be created with a pre-defined keyword Dict (). This keyword accepts key-value pairs as arguments and generates a dictionary by defining its data type based on the data type of the key-value pairs. One can also pre-define the data type of the dictionary if the data type of the values is known.
Use of get () function: Julia provides a pre-defined function to access elements of a Dictionary known as get () function. This function takes 3 arguments: dictionary name, key, and a default value to print if the key is not found.
# Getting the key type of the specified array. The valtype () is an inbuilt function in julia which is used to return the value type of the specified array. A::AbstractArray: Specified array.
Have a look at DataStructures.jl counter.
julia> using DataStructures: counter
julia> a1 = Dict{ASCIIString, Int64}("A"=>1, "B"=>2)
Dict{ASCIIString,Int64} with 2 entries:
"B" => 2
"A" => 1
julia> a2 = Dict{ASCIIString, Int64}("A"=>4, "B"=>1, "C"=>3)
Dict{ASCIIString,Int64} with 3 entries:
"B" => 1
"A" => 4
"C" => 3
julia> merge(counter(a1), counter(a2)).map
Dict{ASCIIString,Int64} with 3 entries:
"B" => 3
"A" => 5
"C" => 3
For anyone looking at this now, counter
is no longer necessary -- use merge(+, a1, a2)
.
julia> a1 = Dict("A"=>1, "B"=>2)
Dict{String,Int64} with 2 entries:
"B" => 2
"A" => 1
julia> a2 = Dict("A"=>4, "B"=>1, "C"=>3)
Dict{String,Int64} with 3 entries:
"B" => 1
"A" => 4
"C" => 3
julia> merge(+, a1, a2)
Dict{String,Int64} with 3 entries:
"B" => 3
"A" => 5
"C" => 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With