Sort A Dictionary By Value Of Each Key-Value Pair
May 16, 2012
You can sort the values in a dictionary using the method keysSortedByValueUsingSelector:. The result is an array of keys from the dictionary, which represent the sorted values of the key-value pair.
Let’s say for example that you have a dictionary that has key-value pairs with an account name and balance:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithDouble:-100.00], @"Account1", [NSNumber numberWithDouble:72.99], @"Account2", [NSNumber numberWithDouble:30.89], @"Account3", [NSNumber numberWithDouble:200.74], @"Account4", nil]; |
Sorting the dictionary is as simple as follows:
NSArray *sortedArray = [dict keysSortedByValueUsingSelector:@selector(compare:)]; NSLog(@"dict: %@", sortedArray); |
The output would look as follows:
dict: (
Account1,
Account3,
Account2,
Account4
) |
The same works equally as well if the value is a string:
NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys: @"ISBN-123", @"Data Structures", @"ISBN-101", @"Computer Graphics", @"ISBN-444", @"Boolean Logic", @"ISBN-222", @"Artificial Intelligence", nil]; NSArray *sortedArray = [dict2 keysSortedByValueUsingSelector:@selector(compare:)]; |
The sorted array of keys would are shown below:
dict: (
"Computer Graphics",
"Data Structures",
"Artificial Intelligence",
"Boolean Logic"
) |



