Swift Program to Remove duplicate elements from Dictionary


In Swift dictionary, we cannot have duplicate keys but can have duplicate values hence in this article we will remove duplicate values from the dictionary. So for that, we use contains() function. This function checks if the dictionary contains duplicate values or not. If the dictionary contains duplicate values, then it will remove them from the resultant dictionary.

Syntax

dict.values.contains(val)

Here, dict is the resultant dictionary in which we will store unique key-value pairs and the contains() function compares two values with each other.

Algorithm

  • Step 1 − Create a dictionary named as myCityRank with key-value pairs.

  • Step 2 − Create an empty dictionary named as resultantDict to store the result.

  • Step 3 − Run a for-in loop to iterate over the key-value pairs of the myCityRank dictionary.

  • Step 4 − Now check for the duplicate values and store only those key-value pairs that are unique in the resultant dictionary.

  • Step 5 − Print the output.

Example

In the following Swift program, we are going to remove duplicate elements from the dictionary. So for that, we will create two dictionaries one with key-value pairs and another one empty. Then will run a for-in loop through each key-value pair present in the myCityRank. For each pair we use contains method to check if the value is present in the resultant dictionary. If the value is not present, then we will add the key-value pair to the resultant dictionary and display the results.

import Foundation
import Glibc

var myCityRank = ["Delhi": 10, "Goa": 3, "Pune": 2, "Jaipur": 2, "Kolkata": 18] 
var resultantDict = [String:Int]()

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

print("Original Dictionary:", myCityRank)
print("Modified New Dictionary:", resultantDict)

Output

Original Dictionary: ["Pune": 2, "Goa": 3, "Jaipur": 2, "Kolkata": 18, "Delhi": 10]
Modified New Dictionary: ["Delhi": 10, "Goa": 3, "Pune": 2, "Kolkata": 18]

Conclusion

So this is how we can remove duplicate elements from the dictionary. As we know the dictionary only contains duplicate values. So we preserve the first occurrence of the duplicate value and remove the result of the duplicate elements. For example, we have 3 duplicate values, so we save the first value in the resultant dictionary and remove the rest 2 duplicate values.

Updated on: 09-May-2023

568 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements