Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap `NSMutableDictionary` key and values in place?

I have a NSMutableDictionary and I want to swap values & keys. i.e, after swapping values becomes keys and its corresponding keys with become values All keys and values are unique. Looking for an in place solution because size is very big . Also, the keys and values are NSString objects

like image 635
Kunal Balani Avatar asked Oct 15 '13 17:10

Kunal Balani


2 Answers

NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:@{
                             @"key1" : @"value1",
                             @"key2" : @"value2"}];

for (NSString *key in [d allKeys]) {
    d[d[key]] = key;
    [d removeObjectForKey:key];
}

NSLog(@"%@", d); // => { value1 : key1,
                 //      value2 : key2 }

Assumptions

  • unique values (as they will become keys)
  • values conform to NSCopying (same as above)
  • no value is equal to any key (otherwise colliding names will be lost in the process)
like image 182
Gabriele Petronella Avatar answered Oct 19 '22 12:10

Gabriele Petronella


Here is another way to invert dictionary. The simplest for me.

NSArray *keys = dictionary.allKeys;
NSArray *values = [dictionary objectsForKeys:keys notFoundMarker:[NSNull null]];
[dictionary removeAllObjects]; // In case of huge data sets release the contents.
NSDictionary *invertedDictionary = [NSDictionary dictionaryWithObjects:keys forKeys:values];
[dictionary setDictionary:invertedDictionary]; // In case you want to use the original dictionary.
like image 45
Tricertops Avatar answered Oct 19 '22 11:10

Tricertops