Remove duplicates in NSdictionary

空扰寡人 提交于 2019-12-02 08:10:52

问题


Is there a way to remove duplicate (key-value) pairs from NSDictionary ?

EDIT: My description was misleading, I have duplicate pairs e.g.
key1-value1
key1-value1
key2-value2
key1-value1
etc..


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2462481/remove-duplicates-in-nsdictionary

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