ios - Sort dictionary based on value and extract the corresponding keys -
i have dictionary data structure in swift key,value pair, want sort dictionary in descending order based on value , top 3 keys corresponding 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 need c, b , a
to first 3 keys associated dictionary's sorted values, (1) sort array values, (2) keys in order sorted array, (3) pull out first 3 keys array:
let dict = ["a":8, "b":23, "c":56, "d":3, "e":9, "f":20] // sort dictionary values let sortedarray = sorted(dict, {$0.1 > $1.1}) // array of keys sorted array let keys = sortedarray.map {return $0.0 } // first 3 keys let firstthreekeys = keys[0..<3] println(firstthreekeys)
Comments
Post a Comment