Remove duplicates in NSdictionary

2019-03-02 21:22发布

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..

3条回答
何必那么认真
2楼-- · 2019-03-02 21:45

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

查看更多
Explosion°爆炸
3楼-- · 2019-03-02 21:48

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

查看更多
可以哭但决不认输i
4楼-- · 2019-03-02 21:53

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.

查看更多
登录 后发表回答