Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Sort keys of NSDictionary based on dictionary entries

OK so I know that dictionaries can't be sorted. But, say I have NSMutableArray *keys = [someDictionary allKeys]; Now, I want to sort those keys, based on the corresponding values in the dictionary (alphabetically). So if the dictionary contains key=someString, then I want to sort keys based on the strings they correspond to. I think its some application of sortUsingComparator but its a little out of my reach at this point.

like image 652
JoshDG Avatar asked Jul 19 '12 06:07

JoshDG


People also ask

How do you sort keys and values in a dictionary?

To correctly sort a dictionary by value with the sorted() method, you will have to do the following: pass the dictionary to the sorted() method as the first value. use the items() method on the dictionary to retrieve its keys and values. write a lambda function to get the values retrieved with the item() method.

Can you sort a dictionary by key C#?

You can't sort a Dictionary<TKey, TValue> - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific.

Can we sort keys in dictionary?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.


1 Answers

NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSString *first = [someDictionary objectForKey:a];
    NSString *second = [someDictionary objectForKey:b];
    return [first compare:second];
}];
like image 99
mask8 Avatar answered Sep 27 '22 17:09

mask8