7

I have a dictionary, [String : Double] with the following data:

Museum1 : 8785.8971799638
Museum2 : 34420.9643422388
Museum3 : 826.467789130732
Museum4 : 304120.342151219

I'd like to sort the dictionary by the double value. I did some research, but all of the examples are deprecated for the current version of Swift

I've tried using this code from Sort Dictionary by values in Swift:

for (k,v) in Array(self.museumsDic).sorted({$0.0 < $1.0}) {
    println("\(k):\(v)")
}

But it doesn't work. How can I sort the dictionary by its values?

Community
  • 1
  • 1
user986690
  • 175
  • 1
  • 3
  • 9
  • Dictionaries have no order, so what would it mean to "sort" a dictionary? What are you _really_ wishing to do? – matt Dec 24 '14 at 17:06
  • 1
    What do you mean by "it didn't work"? That is meaningless. There are only expectations and actual outcomes. What do you expect and what actually happened? – matt Dec 24 '14 at 17:13

3 Answers3

14

It is not clear what your expectations are. There is really no such thing as a sorted dictionary. Your code is basically correct except for a misplaced parenthesis. I tried this:

let d = ["Museum1":8785.8971799638,
"Museum2":34420.9643422388,
"Museum3":826.467789130732,
"Museum4":304120.342151219]

for (k,v) in (Array(d).sorted {$0.1 < $1.1}) {
    println("\(k):\(v)")
}

Result:

Museum3:826.467789130732
Museum1:8785.8971799638
Museum2:34420.9643422388
Museum4:304120.342151219

If you think that's wrong, you need to explain why.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thanks that's perfect. The second number is the distance between the user and a list of museum's. I'm trying to identify the museum closest to the user's location. So yes that's all I wanted, really appreciate it. – user986690 Dec 25 '14 at 08:51
  • 3
    I feel the need to explain this code because it is very hard to decipher. Array(d) creates an array out of the dictionary. Each element of the array is a tuple composed of the key, value pair from the dictionary. The notation $0.1 allows reference within the tuple. It essentially says to sort the tuples according to the 2nd item, i.e. the value. The result of the sort is still an array of tuples which can then be iterated over by 'for (k,v)'. – David Nov 06 '15 at 04:22
  • This code does not sort the dictionary, but it prints the dictionary key/values in sorted form. – S.S.D Apr 30 '18 at 11:38
  • @S.S.D Not true. As my answer says, there is no such thing as a "sorted dictionary". The expression `Array(d).sorted...` gives a sorted derivative of the dictionary — an array. The `print` merely proves that that's what we did. – matt Apr 30 '18 at 13:16
2

In Swift 2.2, this works

for (k,v) in (Array(d).sort {$0.1 < $1.1}) {
    print("\(k):\(v)")
}

Swift 3, it also works:

for (k,v) in (Array(yourDictionary).sorted {$0.1 < $1.1}) {
    print("\(k):\(v)")
}
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53
VladyslavPG
  • 557
  • 1
  • 8
  • 19
1

Simple solution for Swift 4 and above...

let dict = ["Museum1":8785.8971799638,
            "Museum2":34420.9643422388,
            "Museum3":826.467789130732,
            "Museum4":304120.342151219]

let dictSortByValue = dict.sorted(by: {$0.value < $1.value} )

for item in dictSortByValue {
   print("\(item.key) \(item.value) ")
}

// Museum3 826.467789130732 
// Museum1 8785.8971799638 
// Museum2 34420.9643422388 
// Museum4 304120.342151219 

Apparently you can sort a Dictionary in Swift 4--no need to transform into an Array.

John Pavley
  • 5,366
  • 2
  • 14
  • 16
  • 1
    The sort function returns you an array of tuples, not a sorted dictionary. – Daniel Nov 18 '19 at 10:35
  • Yes, you are right, the return is an array of tuples, but anyway it's useful. I have a use case were I use the dictionary to find unique keys out of a data stream and store the lowest value for that key. Later on I sort the dic by the values to have a nice sorted list. The use of a dictionary to find the values is faster than doing it with arrays. .. – Hardy_Germany Mar 13 '20 at 19:39