Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to remove duplicate elements from a dictionary in Swift

2 Answers

0 votes
import Foundation

var dict: [String: Int?] = ["swift": 3, "c": 4, "c++": 3, "python": 3, "java": 5, "rust": 3]

var resultDict = [String: Int]()

for (key, value) in dict {
    if let val = value, !resultDict.values.contains(val) {
        resultDict[key] = val
    }
}

print("Original Dictionary:", dict)
print("New Dictionary:", resultDict)




/*
run:

Original Dictionary: ["c++": Optional(3), "c": Optional(4), "python": Optional(3), "rust": Optional(3), "java": Optional(5), "swift": Optional(3)]
New Dictionary: ["java": 5, "c++": 3, "c": 4]

*/

 



answered Aug 5, 2025 by avibootz
0 votes
import Foundation

var dict = ["swift": 3, "c": 4, "c++": 3, "python": 3, "java": 5, "rust": 3]

var resultDict = [String:Int]()

for(key, value) in dict {
   if !resultDict.values.contains(value) {
      resultDict[key] = value
   }
}

print("Original Dictionary:", dict)
print("New Dictionary:", resultDict)




/*
run:

Original Dictionary: ["swift": 3, "python": 3, "java": 5, "rust": 3, "c++": 3, "c": 4]
New Dictionary: ["c": 4, "java": 5, "swift": 3]

*/

 



answered Aug 5, 2025 by avibootz
...