Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding dictionaries in Julia by summing values of same keys

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.

like image 997
Aung Avatar asked Nov 04 '15 13:11

Aung


People also ask

How to access all keys and values in a dictionary in Julia?

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.

How do I create a dictionary in Julia?

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.

How to use get () function in Julia?

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.

How to get the key type of the specified array in Julia?

# 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.


2 Answers

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
like image 167
Chisholm Avatar answered Nov 17 '22 00:11

Chisholm


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
like image 35
Krisrs1128 Avatar answered Nov 17 '22 02:11

Krisrs1128