Broadcasting algebraic operations between dicts

Viewed 274

I have two dicts and I want to subtract the matching values from the two dicts to generate a third dict.

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

One ugly solution is to overload the subtraction operator but I am not keen to overload for a builtin type like dict for fear of breaking other code.

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

Is there a cleaner way to do algebraic operations on matching values from different dicts?

1 Answers

merge provides the result you want.

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

Note that merge performs a union of the two collections and combines common keys by performing the given operation. So, for example:

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

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