Is it possible to sort a dictionary in Julia?

泄露秘密 提交于 2020-05-12 11:14:14

问题


I have created a dictionary out of two arrays using zip() like

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

Now i want to sort this dictionary by key(list1) or by list2. Can somebody show me a way or function, how to realize it?


回答1:


Sort also takes a by keyword, which means you can do:

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)

Also note that there is a SortedDict in DataStructures.jl, which maintains sort order, and there's an OrderedDict which maintains insertion order. Finally, there's a pull request which would allow direct sorting of OrderedDicts (but I need to finish it up and commit it).




回答2:


While SortedDict may be useful if it is necessary to keep the dictionary sorted, it is often only necessary to sort the dictionary for output, in which case, the following may be what is required:

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

... which produces:

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

We can sort by values with:

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

... which gives:

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


来源:https://stackoverflow.com/questions/29848734/is-it-possible-to-sort-a-dictionary-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!