我有两个dicts,我想从两个dicts中减去匹配值以生成第三个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
Run Code Online (Sandbox Code Playgroud)
一个丑陋的解决方案是重载减法运算符,但我不想为像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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
请注意,merge执行两个集合的并集,并通过执行给定的操作来组合公共键.所以,例如:
W = Dict("w" => 4)
merge(-, B, W)
Dict{String,Int64} with 2 entries:
"w" => 3
"x" => 5
Run Code Online (Sandbox Code Playgroud)