Values(dict) returns key-value pairs after sorting

Hi,

arbeit = Dict("Vollzeit" => length(vollzeit), "Teilzeit" => length(teilzeit), "Minijob" => length(minijob))
arbeit = sort(collect(arbeit), by = x -> x[2])
println(arbeit)
x = collect(keys(arbeit))
println(x)
y = collect(values(arbeit))
println(y)

If line 2 is commented out, println(y) prints the (unsorted) length values as expected and println(x) the corresponding keys. If not, println(y) returns the whole dict and println(x) returns an array [1:8]. Why? How can I get the keys and values of a sorted dict?
Thanks a lot!

Heya,

by collecting a Dict, you turn it into a vector of Pairs. The default dict is inherently unordered and so sorting it does not make sense but sorting the collection makes sense.
In your second line, you assign a (sorted) vector of Pairs to arbeit. We don’t usually consider a vector as having keys but for generality, we can think of the index of an element as its key (same as for the dict where we have dict[key] = value we have vector[index] = value). That’s why you get a range for the keys: it’s the indices, whereas the values are the actual pairs of the dict.

So anyway, to your question. You can either use a sorted Dict (from DataStructures.jl) or

  1. turn the dict into a vector (of pairs)
  2. sort that vector according to your wishes
  3. extract the first and second component of your Pair
arbeit = Dict("Vollzeit" => length(vollzeit), "Teilzeit" => length(teilzeit), "Minijob" => length(minijob))
arbeit = sort(collect(arbeit), by = x -> x[2])
x = map(x -> x[1], arbeit)
y = map(x -> x[2], arbeit)

Note that it’s usually easier to help if your example is self-contained, e.g. by providing dummy values for vollzeit etc. or the dictionary itself.

Thanks for the comprehensive explanation, really useful. I will make my code examples self-contained in the future, thanks for the hint.
Just a quick follow-up question: Are first and second meant to be placeholders for x -> x[i] or are you using a special library or something for these shortcuts? first threw an error in my case.

Oh sorry, I didn’t test my code and misread something in the documentation for Pair - if you have a pair, it has fields first and second - I though those were functions.
So you can either do x -> x.first and x -> x.second or just use indices. I edited my answer to reflect that - sorry for the confusion.

(although I think first should work anyway, being a function that generally works for iterables. second should throw an error though)

Ah, yeah, second threw the error, sorry. Thanks anyway!

I believe you can also use the last function.