Skip to content

mergewith not working properly for OrderedDict #77

@tomyun

Description

@tomyun
julia> d1 = OrderedDict(:A => OrderedDict(:a => 1));
julia> d2 = OrderedDict(:B => OrderedDict(:b => 2));
julia> d3 = OrderedDict(:C => OrderedDict(:c => 3));
julia> d4 = OrderedDict(:D => OrderedDict(:d => 4));

With mergewith introduced in Julia 1.5 superseding merge(f::Function, ...) (JuliaLang/julia#34296), the order of OrderedDict is not maintained properly. Note that the result is in plain Dict.

julia> mergewith(merge, d1, d2, d3, d4)
Dict{Symbol, OrderedDict{Symbol, Int64}} with 4 entries:
  :A => OrderedDict(:a=>1)
  :D => OrderedDict(:d=>4)
  :B => OrderedDict(:b=>2)
  :C => OrderedDict(:c=>3)

Compared to the result from merge which maintains type/order correctly as the behavior is explicitly defined for OrderedDict.

julia> merge(merge, d1, d2, d3, d4)
OrderedDict{Symbol, OrderedDict{Symbol, Int64}} with 4 entries:
  :A => OrderedDict(:a=>1)
  :B => OrderedDict(:b=>2)
  :C => OrderedDict(:c=>3)
  :D => OrderedDict(:d=>4)

Defining mergewith (and perhaps mergewith! too) for OrderedDict in the same way as the custom merge seems to make it working.

function merge(combine::Function, d::OrderedDict, others::AbstractDict...)
K,V = _merge_kvtypes(d, others...)
merge!(combine, OrderedDict{K,V}(), d, others...)
end

julia> OrderedCollections.mergewith(combine, d::OrderedDict, others::AbstractDict...) = begin
           K,V = OrderedCollections._merge_kvtypes(d, others...)
           mergewith!(combine, OrderedDict{K,V}(), d, others...)
       end

julia> mergewith(merge, d1, d2, d3, d4)
OrderedDict{Symbol, OrderedDict{Symbol, Int64}} with 4 entries:
  :A => OrderedDict(:a=>1)
  :B => OrderedDict(:b=>2)
  :C => OrderedDict(:c=>3)
  :D => OrderedDict(:d=>4)

Tested with OrderedCollections 1.4.0 on Julia 1.6.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions