在朱莉娅,如何合并字典?

Nic*_*ler 11 merge dictionary julia

在朱莉娅合并字典的最佳方法是什么?

> dict1 = Dict("a" => 1, "b" => 2, "c" => 3)
> dict2 = Dict("d" => 4, "e" => 5, "f" => 6)
# merge both dicts
> dict3 = dict1 with dict2
> dict3
Dict{ASCIIString,Int64} with 6 entries:
  "f" => 6
  "c" => 3
  "e" => 5
  "b" => 2
  "a" => 1
  "d" => 4
Run Code Online (Sandbox Code Playgroud)

pyt*_*必须死 13

https://docs.julialang.org/en/latest/base/collections/#Base.merge

merge(collection, others...)

Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed.

julia> merge(dict1,dict2)
    Dict{ASCIIString,Int64} with 6 entries:
      "f" => 6
      "c" => 3
      "e" => 5
      "b" => 2
      "a" => 1
      "d" => 4

merge!(collection, others...)
Update collection with pairs from the other collections.

julia> merge!(dict1,dict2)
Dict{ASCIIString,Int64} with 6 entries:
  "f" => 6
  "c" => 3
  "e" => 5
  "b" => 2
  "a" => 1
  "d" => 4

julia> dict1
Dict{ASCIIString,Int64} with 6 entries:
  "f" => 6
  "c" => 3
  "e" => 5
  "b" => 2
  "a" => 1
  "d" => 4
Run Code Online (Sandbox Code Playgroud)

  • 如果好奇,那么如何处理冲突的关键值呢?如果'dict1'中的值'a = 5'和'dict2'中的'a = 7',那么'a'的值在结果字典中会是什么? (2认同)
  • @ niczky12它将更新为7,最后一个值. (2认同)
  • 如果你想保持冲突的值,你可以使用`union(dict1,dict2)`; 但是,这会返回一个`Array`而不是`Dict`. (2认同)

lea*_*nna 7

您可以使用merge。如果Dicts 具有具有相同键的元素,则该键的值将是最后Dict列出的值。

Dict如果你想组合s 中具有相同键的元素,可以使用mergewith(combine, collection, others...)combine是一个接收两个值并返回一个值的函数。看mergewith

文档示例:

julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String,Float64} with 2 entries:
  "bar" => 42.0
  "foo" => 0.0

julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String,Int64} with 2 entries:
  "bar" => 4711
  "baz" => 17

julia> mergewith(+, a, b)
Dict{String,Float64} with 3 entries:
  "bar" => 4753.0
  "baz" => 17.0
  "foo" => 0.0
Run Code Online (Sandbox Code Playgroud)