如何在Julia中按值对字典排序?

时间:2020-03-18 16:28:28

标签: julia

我有两个数组:

a = [11,22,33,44,55]
b = [66,77,88,99,100]

我曾经通过以下操作创建字典:

combined_dict = Dict(zip(a, b))

如何按值对字典 进行排序?

3 个答案:

答案 0 :(得分:3)

内置字典类型(Dict)是无序的,因此不清楚您要的是什么-无法排序。如果要订购字典,可以使用OrderedCollections包中的OrderedDict

julia> a = [11,22,33,44,55];

julia> b = [100,99,88,77,66];

julia> combined_dict = OrderedDict(zip(a, b))
OrderedDict{Int64,Int64} with 5 entries:
  11 => 100
  22 => 99
  33 => 88
  44 => 77
  55 => 66

为了按值排序,您可以使用byvalue=true作为关键字参数进行排序(byvalue=false是默认值,即按键排序):

julia> sort(combined_dict; byvalue=true)
OrderedDict{Int64,Int64} with 5 entries:
  55 => 66
  44 => 77
  33 => 88
  22 => 99
  11 => 100

答案 1 :(得分:2)

要按字典顺序对元组进行排序,只需执行以下操作:

julia> sort(collect(zip(values(combined_dict), keys(combined_dict))))
5-element Array{Tuple{Int64,Int64},1}:
 (66, 11) 
 (77, 22) 
 (88, 33) 
 (99, 44) 
 (100, 55)

请参阅此帖子以供参考:Is it possible to sort a dictionary in Julia?

Learn more about the sort function here.

Learn more about the collect function here.

Learn more about the zip function here.

答案 2 :(得分:0)

为了对字典值进行排序,不需要使用 OrderedDict
对于您的用例,使用 sort 函数就足够了。

julia> a = [11,22,33,44,55];

julia> b = [100,99,88,77,66];

julia> combined_dict = Dict{Int, Int}(zip(a, b))
Dict{Int64, Int64} with 5 entries:
  22 => 99
  55 => 66
  33 => 88
  11 => 100
  44 => 77

julia> sort(combined_dict, byvalue=true)
OrderedDict{Int64, Int64} with 5 entries:
  55 => 66
  44 => 77
  33 => 88
  22 => 99
  11 => 100

Julia 1.6 上测试

相关问题