在字典之间广播代数运算

时间:2018-09-02 21:05:26

标签: dictionary julia

我有两个字典,我想从两个字典中减去匹配值以生成第三个字典。

A = Dict("w" => 2, "x" => 3)
B = Dict("x" => 5, "w" => 7)
# Ideally I could go B .- A and get a dict like 
C = Dict("w" => 5, "x" => 2)
# but I get ERROR: ArgumentError: broadcasting over dictionaries and `NamedTuple`s is reserved

一个丑陋的解决方案是重载减法运算符,但我不希望重载像dict这样的内置类型,因为担心会破坏其他代码。

import Base.-
function -(dictA::Dict, dictB::Dict)
   keys_of_A = keys(dictA)
   subtractions = get.(Ref(dictB), keys_of_A, 0) .- get.(Ref(dictA), keys_of_A, 0)
   return Dict(keys_of_A .=> subtractions)
end

是否有一种更干净的方法来对来自不同字典的匹配值进行代数运算?

1 个答案:

答案 0 :(得分:5)

merge提供您想要的结果。

A = Dict("w" => 2, "x" => 3)
B = Dict("x" => 5, "w" => 7)
C = merge(-, B, A)

Dict{String,Int64} with 2 entries:
  "w" => 5
  "x" => 2

请注意,merge执行两个集合的并并通过执行给定的操作来组合公用密钥。因此,例如:

W = Dict("w" => 4)
merge(-, B, W)

Dict{String,Int64} with 2 entries:
  "w" => 3
  "x" => 5
相关问题