Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to sort a dictionary in Julia?

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?

like image 749
team17 Avatar asked Apr 24 '15 13:04

team17


2 Answers

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).

like image 105
kmsquire Avatar answered Nov 17 '22 18:11

kmsquire


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)
like image 30
Simon Avatar answered Nov 17 '22 18:11

Simon