是否可以在 Julia 中对字典进行排序?

Is it possible to sort a dictionary in Julia?

我使用 zip() like

从两个数组中创建了一个字典
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,19]
dictionary1 = Dict(zip(list1,list2))

现在我想按 key(list1)list2 对这本词典进行排序。谁能告诉我一个方法或功能,如何实现它?

虽然 SortedDict 如果需要保持字典排序可能会有用,但通常只需要对字典进行排序以进行输出,在这种情况下,可能需要以下内容:

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,19]
dictionary1 = Dict(zip(list1,list2))
sort(collect(dictionary1))

... 产生:

5-element Array{(Int64,Int64),1}:
 (1,6) 
 (2,7) 
 (3,8) 
 (4,9) 
 (5,19)

我们可以按值排序:

sort(collect(zip(values(dictionary1),keys(dictionary1))))

... 这给出:

5-element Array{(Int64,Int64),1}:
 (6,1) 
 (7,2) 
 (8,3) 
 (9,4) 
 (19,5)

排序也需要一个 by 关键字,这意味着您可以:

julia> sort(collect(dictionary1), by=x->x[2])
5-element Array{Tuple{Int64,Int64},1}:
 (1,6)
 (2,7)
 (3,8)
 (4,9)
 (5,19)

另请注意,DataStructures.jl 中有一个 SortedDict,它保持排序顺序,还有一个 OrderedDict 保持 插入 顺序.最后,有一个 pull request 允许直接排序 OrderedDicts(但我需要完成并提交)。

sort 函数的 byvalue 关键字(或 mutating/in 位置排序的 sort! 关键字)对于按值的顺序对字典进行排序很有用(相对于他们的钥匙)。结果将是来自 OrderedCollections.jl (it's also re-exported by DataStructures.jl).

的 OrderedDict 类型
list1 = [2,1,3,4,5]
list2 = [9,10,8,7,6]
dictionary1 = Dict(zip(list1,list2))

按值排序(即按 list2):

sort(dictionary1; byvalue=true)

输出:

OrderedDict{Int64, Int64} with 5 entries:
  5 => 6
  4 => 7
  3 => 8
  2 => 9
  1 => 10

按键排序(即按 list1):

sort(dictionary1)

输出:

OrderedDict{Int64, Int64} with 5 entries:
  1 => 10
  2 => 9
  3 => 8
  4 => 7
  5 => 6