删除NSdictionary中的重复 [英] Remove duplicates in NSdictionary

查看:169
本文介绍了删除NSdictionary中的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从NSDictionary中删除重复(键值)对?

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

编辑:
我的描述是误导的,我有重复的对,例如

key1-value1

key1-value1

key2-value2

key1-value1

etc ..

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

推荐答案

反转键值不是一个好主意,因为不是所有的值都可以是键。
你可以这样做:

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

// dict是原始字典,newDict新字典有重复的。

// 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也可以使用lastObject而不是objectAtIndex:0为其他键留下dup对象

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

这篇关于删除NSdictionary中的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆