Home > Mobile >  How to remove duplicate keys from dictionary?
How to remove duplicate keys from dictionary?

Time:05-23

I'm using Xcode 13.4. I'm working on a dictionary based app. I've an issue with dictionary that I've thousands of keys in dictionary. Now I've an error

Thread 1: Fatal error: Dictionary literal contains duplicate keys

How to get ride of this error? I've tried many answers from StackOverFlow but i can't get solution about my lengthy dictionary.

enter image description here

let dict : [String:String] = [
        "ik4":"一",
        "sioh8":"一",
        "cik4": "七",
        "ding1": "丁",
        "diong7": "丈",
        "diong5":"丈",
.........]

CodePudding user response:

Each dictionary key MUST be unique. Its your responsibility if you are trying to create manually dictionary, Keys should be unique.

As such no api to remove duplicate keys from dictionary.

CodePudding user response:

If it's important to check also the values of the duplicate keys you have to do it manually.

If not an easy way to remove the duplicate keys is to make the dictionary a JSON string and decode end re-encode the JSON.

  • Copy the entire dictionary literal and paste it into a Playground

  • Replace [] with {} and wrap the literal in """ like

    let dict = """
      {
          "ik4":"一",
          "sioh8":"一",
          "cik4": "七",
          "ding1": "丁",
          "diong7": "丈",
          "diong5":"丈",
          "cik4": "七"
      }
      """
    
  • Run this code

    do {
        let input = try JSONDecoder().decode([String:String].self, from: Data(dict.utf8))
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        let output = try encoder.encode(input)
        let string = String(data: output, encoding: .utf8)!
        print(string)
    } catch {
        print(error)
    }
    
  • Copy the result in the Console between {} and paste it into your project.

  • Related