Sort Dictionary by Key Value

后端 未结 3 1038
萌比男神i
萌比男神i 2020-11-28 14:06
let dict: [String:Int] = [\"apple\":5, \"pear\":9, \"grape\":1]

How do you sort the dictionary based on the Int value so that the outp

相关标签:
3条回答
  • 2020-11-28 14:24

    You need to sort your dictionary values, not your keys. You can create an array of tuples from your dictionary sorting it by its values as follow:

    Xcode 9 • Swift 4 or Xcode 8 • Swift 3

    let fruitsDict = ["apple": 5, "pear": 9, "grape": 1]
    let fruitsTupleArray = fruitsDict.sorted{ $0.value > $1.value }
    
    fruitsTupleArray // [(.0 "pear", .1 9), (.0 "apple", .1 5), (.0 "grape", .1 1)]
    
    for (fruit,votes) in fruitsTupleArray {
        print(fruit,votes)
    }
    
    fruitsTupleArray.first?.key   // "pear"
    fruitsTupleArray.first?.value   // 9
    

    To sort your dictionary using your keys

    let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key }
    fruitsTupleArray  // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)]
    

    To sort your dictionary using its keys and localized comparison:

    let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending  }
    
    0 讨论(0)
  • 2020-11-28 14:32

    Dictionaries can't be sorted. Generally, when I need things sorted from a dictionary, I will make a separate array of my dictionary keys.

    In your case, make an array of the keys, sort them by comparing their values in the dictionary.

    0 讨论(0)
  • 2020-11-28 14:37

    It can be achieved by using the below implementation

    let sortedDictionary = unsortedDictionary.sorted{$0.key > $1.key}

    0 讨论(0)
提交回复
热议问题