1

I have a dictionary with string as key and an array of int as values , i need to sort the dictionary based on keys and the array value should also be sorted.

var dicNumArray : Dictionary<String , [Int]> = ["q":[4,3,2,1,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[0,88,66,542,321]]

The result i need is the dictionary itself where it is sorted by keys and respective values are also sorted.

Nassif
  • 1,113
  • 2
  • 14
  • 34
  • 1
    What type of output are you expecting? Are you printing something, or creating a new data structure (an array for instance?) Have you had trouble with the `.sorted` method? – Rob Napier May 11 '18 at 03:55
  • 3
    dictionaries have no order. check this out: https://stackoverflow.com/a/29603477/6642629 – koropok May 11 '18 at 03:57

3 Answers3

2

You can apply sorted to each the value of the key-value pair of a dictionary using mapValues

And then, you can just use sorted with a predicate comparing the keys of the dictionary.

let result = dicNumArray.mapValues { $0.sorted() }
                        .sorted { $0.key < $1.key }

This will return an array of key-value pair tuples.

Since, dictionaries can't be trusted with order, working with an array of the key-value pairs is the next best approach.

We can use .key and .value to get the respective values.

result.first?.key     // First key
result.first?.value   // First value
Sam
  • 649
  • 5
  • 13
1

you can apply sort key , then map to sorted by array

let sortedKeysAndValues = dicNumArray.sorted(by: {$0.0 < $1.0}).map { [$0.key:$0.value.sorted(by: <)]}.flatMap({$0})
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
1

Dictionaries don't have an order in Swift. Having said that, you can do something like this

var dicNumArray : Dictionary<String , [Int]> = ["q":[4,3,2,1,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[0,88,66,542,321]]

func sortData() {
    for (key, value) in dicNumArray {
        dicNumArray[key] = value.sorted(by: { $0 < $1 })
    }
}

sortData()

This will sort array for each key. Once that's done, you can do something like

let keys = Array(dicNumArray.keys).sorted(by: { $0 < $1 })

This will give you a sorted array of dictionary keys. You can test it as follows

TEST

for key in keys {
    print("\(key): \(dicNumArray[key]!)")
}

OUTPUT

a: [2, 3, 4, 5, 5]
q: [1, 2, 3, 4, 5]
s: [4, 43, 123, 123, 132]
t: [0, 66, 88, 321, 542]
Malik
  • 3,763
  • 1
  • 22
  • 35