从Swift 3中的字典中删除重复值

时间:2017-04-09 11:22:02

标签: ios dictionary swift3

嗨我有一本字典,我只是想删除重复的值(用它们的键),如下所示:

var myDict : [Int:String] = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]

期望的输出:

[1: "test1", 2: "test2", 4: "test4"]

4 个答案:

答案 0 :(得分:4)

在我看来,所有其他答案都会有O(n ^ 2)表现。

这是一个应该在O(n)时间内运行的解决方案:

var sourceDict = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]

var uniqueValues = Set<String>()
var resultDict = [Int:String](minimumCapacity: sourceDict.count)

//The reserveCapacity() function doesn't exist for Dictionaries, as pointed
//out by Hamish in the comments. See the initializer with minimumCapacity, 
//above. That's the way you have to set up a dictionary with an initial capacity.
//resultDict.reserveCapacity(sourceDict.count)

for (key, value) in sourceDict {
  if !uniqueValues.contains(value) {
    uniqueValues.insert(value)
    resultDict[key] = value
  }
}

对于小词典,差异微不足道,但如果你有一个包含数百(或数千)个键/值对的词典,那么n ^ 2算法的性能开始变得真的坏。

答案 1 :(得分:1)

您可以使用此代码

let newDict = myDict.keys.sorted().reduce([Int:String]()) { (res, key) -> [Int:String] in
    guard let value = myDict[key], !res.values.contains(value) else { return res }
    var res = res
    res[key] = value
    return res
}
  

请记住,字典未排序,因此输出可能是这样的

[2: "test2", 4: "test4", 1: "test1"]

请参阅 @Duncan 提供的answer以获得更快的解决方案。

答案 2 :(得分:1)

var myDict: [Int:String] = [1:"test1", 2:"test2", 3:"test1", 4:"test4"]

var result: [Int:String] = [:]
for (key, value) in myDict {
    if !result.values.contains(value) {
        result[key] = value
    }
}

print(result)

答案 3 :(得分:1)

这是做同样的另一种方式

var myDict : [Int:String] = [1:"test1", 2:"test1", 3:"test1", 4:"test4", 5:"test4"]

var newDict:[Int: String] = [:]

for (key, value) in myDict {
    print(key, value)

    let keys = myDict.filter {
        return $0.1.contains(value)
        }.map {
            return $0.0
    }

    if keys.first == key {
        newDict[key] = value
    }
}

print(newDict)