Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
James Lambert
Courses Plus Student 14,477 PointsWhat would be a good way to return the key values in a dictionary in order of highest to lowest.
I have a dictionary of Integers like var myDictionary = Int: Int myDictionary = [1:0, 2:0, 3:0, 4:0, 5:0]
As the user interacts with the app the values will change. It's how I am trying to keep track of certain choices the user makes.
As the user progresses through the app they might end up with a result like: myDictionary = [1:12, 2:4, 3:9, 4:1, 5:8]
I wan't to display the users progress. letting them know that 1 is the highest, followed by 3, 5, 3, and last 4.
can use this to find the highest:
var largestReturn = 0 var largestKey = 0
for var a = 0; a < myDictionary.count; a ++ { if myDicitonary[a] > largestReturn { largestReturn = myDictionary[a]! largestKey = a } } println("The largest number is (largestReturn!) at the key (largestKey)
This return the largest number. I am trying to figure out a good way to sort the rest.
1 Answer
Hayes McCardell II
643 PointsHere's one idea.
Create a new dictionary that will store the sorted result.
Create a copy of the unsorted dictionary so you can mess with it without destroying your data.
Iterate through the unsorted copy and find the smallest value.
{
Store it in your new dictionary.
Remove that key value pair from your unsorted copy
Repeat the number of times equal to your original dictionary length
}
Point the unsorted dictionary to point to your new sorted dictionary.