Way to recreate OrderedDict under new sorting function?

Lets say you have an ordered dict:

using DataStructures
cur_dict = OrderedDict()

And you then do two rounds of key inserts:

foreach(cur_value -> cur_dict[cur_value] = cur_value+rand()/2, 1:2:9)
foreach(cur_value -> cur_dict[cur_value] = cur_value+rand()/4, 2:4:10)

This gives:

> cur_dict
OrderedDict{Any,Any} with 8 entries:
  1  => 1.14616
  3  => 3.2501
  5  => 5.26185
  7  => 7.40121
  9  => 9.20038
  2  => 2.02592
  6  => 6.11011
  10 => 10.2155

Is there a way to reorder the OrderedDict, so that the keys are sorted under some new sort function?

// i.e. by sort(collect(keys(cur_dict))) == [1, 2, 3, 5, 6, 7, 9, 10]

A simple way is to just create a new OrderedDict.

1 Like

OrderedDicts are simply dictionaries whose entries have a particular order. For OrderedDicts (and OrderedSets ), order refers to insertion order , which allows deterministic iteration over the dictionary or set

So there is no sort function beyond insertion order. You could presort your information and then insert it in that sorted order.

Maybe a SortedDict is better for you. see https://juliacollections.github.io/DataStructures.jl/latest/sorted_containers.html

3 Likes