[swift] Sort Dictionary by keys

I want to sort a dictionary in Swift. I have a dictionary like:

"A" => Array[]
"Z" => Array[]
"D" => Array[]

etc. I want it to be like

"A" => Array[]
"D" => Array[]
"Z" => Array[]

etc.

I have tried many solutions on SO but no one worked for me. I am using XCode6 Beta 5 and on it some are giving compiler error and some solutions are giving exceptions. So anyone who can post the working copy of dictionary sorting.

This question is related to swift sorting dictionary

The answer is


Swift 2.0

Updated version of Ivica M's answer:

let wordDict = [
     "A" : [1, 2],
     "Z" : [3, 4],
     "D" : [5, 6]
]

let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)") // 

Swift 3

wordDict.sorted(by: { $0.0 < $1.0 })

Notice:

Don't be surprised that the resulting type is an array rather than a dictionary. Dictionaries cannot be sorted! The resulting data-type is a sorted array, just like in @Ivica's answer.


For Swift 4 the following has worked for me:

let dicNumArray = ["q":[1,2,3,4,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[00,88,66,542,321]]

let sortedDic = dicNumArray.sorted { (aDic, bDic) -> Bool in
    return aDic.key < bDic.key
}

Swift 4 & 5

For string keys sorting:

dictionary.keys.sorted(by: {$0.localizedStandardCompare($1) == .orderedAscending})

Example:

var dict : [String : Any] = ["10" : Any, "2" : Any, "20" : Any, "1" : Any]

dictionary.keys.sorted() 

["1" : Any, "10" : Any, "2" : Any, "20" : Any]

dictionary.keys.sorted(by: {$0.localizedStandardCompare($1) == .orderedAscending})

["1" : Any, "2" : Any, "10" : Any, "20" : Any]


In swift 4 you can write it smarter:

let d = [ 1 : "hello", 2 : "bye", -1 : "foo" ]
d = [Int : String](uniqueKeysWithValues: d.sorted{ $0.key < $1.key })

Swift 5

Input your dictionary that you want to sort alphabetically by keys.

// Sort inputted dictionary with keys alphabetically.
func sortWithKeys(_ dict: [String: Any]) -> [String: Any] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [String: Any] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

dict.sorted(by: { $0.key < $1.key }) by it self returns a tuple (value, value) instead of a dictionary [value: value]. Thus, the for loop parses the tuple to return as a dictionary. That way, you put in a dictionary & get a dictionary back.


If you want to iterate over both the keys and the values in a key sorted order, this form is quite succinct

let d = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

Swift 1,2:

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

Swift 3+:

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

For Swift 3, the following sort returnes sorted dictionary by keys:

let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]

let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })

print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]

"sorted" in iOS 9 & xcode 7.3, swift 2.2 is impossible, change "sorted" to "sort", like this:

let dictionary = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedKeysAndValues = Array(dictionary).sort({ $0.0 < $1.0 })
print(sortedKeysAndValues)

//sortedKeysAndValues = ["desert": 2.99, "main course": 10.99, "salad": 5.99]

In Swift 5, in order to sort Dictionary by KEYS

let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.0 < $1.0 })

In order to sort Dictionary by VALUES

let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.1 < $1.1 })

Swift 3 is sorted(by:<)

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(by:<) // ["A", "D", "Z"]

For Swift 3 the following has worked for me and the Swift 2 syntax has not worked:

// menu is a dictionary in this example

var menu = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]

let sortedDict = menu.sorted(by: <)

// without "by:" it does not work in Swift 3

I tried all of the above, in a nutshell all you need is

let sorted = dictionary.sorted { $0.key < $1.key }
let keysArraySorted = Array(sorted.map({ $0.key }))
let valuesArraySorted = Array(sorted.map({ $0.value }))

This is an elegant alternative to sorting the dictionary itself:

As of Swift 4 & 5

let sortedKeys = myDict.keys.sorted()

for key in sortedKeys {
   // Ordered iteration over the dictionary
   let val = myDict[key]
}

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python