OdieO
OdieO

Reputation: 7004

Sort NSDictionary by value within an inner nested NSDictionary

I'm working on a language learning app. So I have an NSMutableDictionary with 'word' as keys. The objects for these keys are nested NSDictionaries with the keys 'frequency' and 'count'. NSNumbers are the objects for 'frequency' and 'count'.

Here is the initializing code:

 NSString* path = [[NSBundle mainBundle] pathForResource:@"french_top_50000"
                                                     ofType:@"txt"];
 NSString *fh = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
 self.userWordlist = [[NSMutableDictionary alloc] init];

 for (NSString *word in fh) {
    NSArray *keyArray = [[NSArray alloc] initWithObjects:@"frequency", @"count", nil];
    NSArray *objectArray = [[NSArray alloc] initWithObjects:frequency, count, nil];
    NSDictionary *detailsDict = [[NSDictionary alloc] initWithObjects:objectArray forKeys:keyArray];

    [self.userWordlist setObject:detailsDict forKey:word];
 }

I'm displaying part of this list in a table, and I want to sort by 'frequency', one of the inner keys. I can't figure out how to do this.


In case the first thought is, "Why did you store this in a nested dictionary?", I wanted the words to be keys because in other parts of the app I frequently search to see if a word is in the NSMutableDictionary.

I thought about having a flat dictionary with the following keys: 'word','frequency','count' ... but I'd have to enumerate to check for inclusion of words.

If there are any suggestions for a better data structure strategy I'd love to hear them. I'm going to be checking very frequently for inclusion of 'words' and less frequently will be sorting based on 'frequency' or 'count'.


I've seen lots of question similar to this but they're all for flat dictionaries.

Upvotes: 0

Views: 1432

Answers (1)

ehope
ehope

Reputation: 516

If I understand correctly, use keysSortedByValueUsingComparator: like this:

    NSArray *keysByFrequency = [self.userWordlist keysSortedByValueUsingComparator:^NSComparisonResult(NSDictionary* obj1, NSDictionary* obj2) {
         return [obj1[@"frequency"] compare:obj2[@"frequency"]];
    }];

Then you can iterate keys sorted by their frequency

    for (NSString *word in keysByFrequency){
         NSDictionary *detailsDict = self.userWordList[word];
         // Do whatever...
    }

Upvotes: 5

Related Questions