Katy P
Katy P

Reputation: 37

Sort dictionary based on value and extract the corresponding keys

I have a dictionary data structure in Swift with key,value pair, I want to sort the dictionary in descending order based on the value and then get the top 3 keys corresponding to top 3 values.

example:

before sort:

Dictionary<'A', 8>
Dictionary<'B', 23>
Dictionary<'C', 56>
Dictionary<'D', 3>
Dictionary<'E', 9>
Dictionary<'F', 20>

After sort:

 Dictionary<'C', 56>
 Dictionary<'B', 23>
 Dictionary<'F', 20>
 Dictionary<'E', 9>
 Dictionary<'A', 8>
 Dictionary<'D', 3>

so I need C, B and A

Upvotes: 2

Views: 484

Answers (3)

MirekE
MirekE

Reputation: 11555

In Swift 2 you can do for example this:

let dict = ["A":8, "B":23, "C":56, "D":3, "E":9, "F":20]

let sa = dict.sort({$0.1 > $1.1}).prefix(3).map { $0.0 } // ["C", "B", "F"]

Upvotes: 2

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

To get the first three keys associated with the dictionary's sorted values, (1) sort the array by its values, (2) get the keys in order from that sorted array, then (3) pull out the first 3 keys from that array:

let dict = ["A":8, "B":23, "C":56, "D":3, "E":9, "F":20]

// Sort the dictionary by its values
let sortedArray = sorted(dict, {$0.1 > $1.1})

// Get an array of the keys from the sorted array
let keys = sortedArray.map {return $0.0 }

// Get the first three keys
let firstThreeKeys = keys[0..<3]
println(firstThreeKeys)

Upvotes: 3

tuledev
tuledev

Reputation: 10317

for (key,value) in (Array(arr).sorted {$0.1 < $1.1}) {
    println("\(key):\(value)")
}

Upvotes: 0

Related Questions