Sort dictionary by key value

let dict: [String:Int] = ["apple":5, "pear":9, "grape":1] 

How do you sort a dictionary based on an Int value so that the output is:

 sortedDict = ["pear":9, "apple":5, "grape":1] 

Current attempt (not sorted correctly):

 let sortedDict = sorted(dict) { $0.1 > $1.1 } 
+3
sorting swift
Jul 20 '15 at 23:04
source share
2 answers

You need to sort the dictionary values, not the keys. You can create an array of tuples from your dictionary by sorting it by its values ​​as follows:

Xcode 9 β€’ Swift 4 or Xcode 8 β€’ Swift 3

 let fruitsDict = ["apple": 5, "pear": 9, "grape": 1] let fruitsTupleArray = fruitsDict.sorted{ $0.value > $1.value } fruitsTupleArray // [(.0 "pear", .1 9), (.0 "apple", .1 5), (.0 "grape", .1 1)] for (fruit,votes) in fruitsTupleArray { print(fruit,votes) } fruitsTupleArray.first?.key // "pear" fruitsTupleArray.first?.value // 9 



Sorting a dictionary using keys

 let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key } fruitsTupleArray // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)] 

Sorting a dictionary using its keys and localized comparison:

 let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending } 
+15
Jul 21 '15 at 1:20
source share

Dictionaries cannot be sorted. Typically, when I need things sorted by dictionary, I will create a separate array of keys for the dictionary.

In your case, create an array of keys, sort them by comparing their values ​​in the dictionary.

+4
Jul 20 '15 at 23:49
source share



All Articles