Home
Swift
Sort Dictionary: Keys and Values
This page was last reviewed on Sep 16, 2023.
Dot Net Perls
Sort dictionary. In Swift 5.8, the dictionary is a collection that does not have any specific ordering to its keys and values. But we can copy the dictionary's contents and sort the entries.
sort
Dictionary
By converting the dictionary into an array, we can access each Dictionary entry for sorting. We can specify how to sort entries with a closure.
Example. To begin, we have a dictionary and want to sort its keys and values in various ways. We use an ascending sort here, but descending could be done as well.
Part 1 We create a dictionary with 3 keys, each with an associated value. The keys are Strings, and the values are Ints.
Part 2 Here we convert the dictionary into an array by using Array(). This gives us an array of Entry instances.
Part 3 We sort in an ascending way with the "less than" character, which is shorthand for a closure than sorts the elements.
Part 4 We display the elements after the first sorting operation. The keys are now ordered alphabetically.
Part 5 To sort by values, we can specify a closure, which is longer to type out and read, but works in a similar way.
Part 6 Finally we display the entries in our array again. They have been sorted now by the value (the Ints).
// Part 1: create a dictionary. let animals = ["beta": 0, "zeta": 900, "alpha": 10] // Part 2: Convert the dictionary into an array. var copy = Array(animals) // Part 3: sort by key of each element from low to high (alphabetical order). copy.sort(by: <) // Part 4: loop over and display sorted elements. for element in copy { print(element) } print() // Part 5: sort by value with closure. copy.sort(by: { (a, b) -> Bool in return a.value < b.value }) // Part 6: display again. for element in copy { print(element) }
(key: "alpha", value: 10) (key: "beta", value: 0) (key: "zeta", value: 900) (key: "beta", value: 0) (key: "alpha", value: 10) (key: "zeta", value: 900)
By converting other types like Dictionary into arrays, we can access powerful built-in functions like sort(). This gives us a convenient way to modify and display data.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 16, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.