Remove duplicates in NSdictionary

旧巷老猫 提交于 2019-12-02 06:22:25
Vladimir

reversing key-value is not good idea because not all values can be keys. You can do it with:

// dict is original dictionary, newDict new dictionary withot duplicates.

NSMutableDictionary * newDict = [NSMutableDictionary dictionaryWithCapacity:[dict count]];
for(id item in [dict allValues]){
    NSArray * keys = [dict allKeysForObject:item];
    [newDict setObject:item forKey:[keys objectAtIndex:0]];
}

yuo can also use lastObject instead of objectAtIndex:0 to leave other key for dup objects

One way is to put the key/value pairs into a dictionary by value/key and then converting that back to key/value.

I can't think of a built-in method.

If you iterate over the values, allKeysForObject: will give you an array of keys for each value and if you have more more than one key, that value has duplicates.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!