1

I have a dictionary of type [Int : String] that I want to sort by the keys and then convert it into array. For example:

let dict : [Int : String] = [18 : "Maya", 13 : "Ori", 49 : "Mom", 21 : "Lital", 51 : "Dad"]
// After convertion:
// ["Ori", "Maya", "Lital", "Mom", "Dad"]

How do I do that? I only know how to convert dict into array by doing Array(dict.values), but it doesn't make that in the right order.

Thanks

אורי orihpt
  • 2,358
  • 2
  • 16
  • 41
Daisy the cat
  • 372
  • 3
  • 11
  • 1
    `let sortedValuesByKeys = dict.sorted(by: { $0.key < $1.key }).map { $0.1 }` should do the trick. Since Dictionaries aren't ordered, we sort a tuple (key, value), that we sort, then get (map) only the values. – Larme Jul 21 '20 at 12:34

2 Answers2

5

Dictionary already has a sorted method that takes a closure that defines the sorting function. You can sort by keys in the closure, then simply map over the resulting tuples to get the values only.

let sortedDictKeys = dict.sorted(by: { $0.key < $1.key }).map(\.value)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 1
    You can use keypath when mapping the values `map(\.1)` or for batter readability `map(\.value)` – Leo Dabus Jul 21 '20 at 15:56
  • 1
    @LeoDabus `.map(\.value)` does read better, updated my answer, thanks! – Dávid Pásztor Jul 21 '20 at 15:58
  • 1
    To sort a dictionary using its keypath you can check this [post](https://stackoverflow.com/a/63018749/2303865) `dict.sorted(\.key).map(\.value)` or `dict.sorted(\.key, by: >).map(\.value)` – Leo Dabus Jul 21 '20 at 16:29
1

I have converted in the following way:-

 let dict : [Int : String] = [18 : "Maya", 13 : "Ori", 49 : "Mom", 21 : "Lital", 51 : "Dad"]
 let sortedDict = dict.sorted { $0.key < $1.key }
 let sortedDictArray = Array(sortedDict.map({ $0.value }))
 print(sortedDictArray)

The output is:-

 ["Ori", "Maya", "Lital", "Mom", "Dad"]
Ashutosh Mishra
  • 1,679
  • 1
  • 13
  • 16