Print top 2 highest scores in dictonary

The code prints out the highest score in the dictionary. How can I print the 2nd highest score as well. I want to print the top 2 scores.

    import UIKit

 var people: [[String:Any]] = [
[
    "firstName": "Sam",
    "lastName": "Newton",
    "score": 13
],
[
    "firstName": "Joe",
    "lastName": "Mckenzie",
    "score": 23
],


   ]

var topPerson = people[0]
 var bestScore = topPerson["score"] as! Int
  var bestScore1 = topPerson["score"] as! Int

 for person in people {
if let score = person["score"] as? Int {
    if bestScore < score  {
        bestScore = score
        topPerson = person
    }
}
  }

  if let first = topPerson["firstName"] as? String,
let second = topPerson["lastName"] as? String  {
print("\(first) \(second)")
    }

@timswift Thanks very much for your question!

What I would suggest is to sort the dictionaries in the array, based on the property “score”, from largest to smallest. Once they are sorted, you can simply print the objects from the first two indices in the array. :slight_smile:

I hope this helps!

All the best!

let topTwoScorers = people.sorted {
    let a = $0["score", default: 0] as! Int
    let b = $1["score", default: 0] as! Int
    return a > b
}.prefix(2)

Now you have an array of either 0, 1, or 2 elements, with the highest scoring person as the first element. If it’s not guaranteed that the “score” element will be an Integer you’ll need to do some extra type checking to prevent a crash.

This topic was automatically closed after 166 days. New replies are no longer allowed.