【问题标题】:In Julia, how to merge a dictionary?在 Julia 中,如何合并字典?
【发布时间】:2016-07-14 10:16:52
【问题描述】:

在 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

【问题讨论】:

    标签: dictionary merge julia


    【解决方案1】:

    您可以使用merge。如果Dicts 的元素具有相同的键,则该键的值将是最后列出的Dict。如果要组合Dicts 中具有相同key 的元素,可以使用merge(combine, collection, others...)combine 是一个接收两个值并返回一个值的函数。

    docs 的示例:

    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> merge(+, a, b)
    Dict{String,Float64} with 3 entries:
      "bar" => 4753.0
      "baz" => 17.0
      "foo" => 0.0
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 只是出于好奇,如何处理冲突的键值?如果我在“dict1”中有值“a =5”,在“dict2”中有值“a =7”,那么结果字典中的“a”值是多少?
      • 如果你想保留冲突的值,你可以使用union(dict1, dict2);但是,这将返回 Array 而不是 Dict
      猜你喜欢
      • 2017-04-03
      • 2014-07-22
      • 2017-04-24
      • 2016-09-03
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      相关资源
      最近更新 更多