通过对相同键的值进行求和,在Julia中添加词典

时间:2015-11-04 13:36:25

标签: dictionary counter julia

我在朱莉娅有两个词典a1a2

a1 = {"A"=>1, "B"=>2}
a2 = {"A"=>4, "B"=>1, "C"=>3}

我想把它结合起来得到这个。

final={"A"=>5, "B"=>3, "C"=>3}

在Python中,我将字典转换为集合计数器并将它们组合在一起。

2 个答案:

答案 0 :(得分:5)

查看DataStructures.jl计数器。

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

答案 1 :(得分:2)

对于现在正在查看此问题的任何人,都不再需要counter - 使用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