IT

키를 기준으로 사전 정렬

lottoking 2020. 7. 30. 09:39
반응형

키를 기준으로 사전 정렬


Swift에서 사전을 정렬하고 싶습니다. 나는 같은 사전을 가지고있다 :

"A" => Array[]
"Z" => Array[]
"D" => Array[]

등 나는 그것을 원합니다

"A" => Array[]
"D" => Array[]
"Z" => Array[]

기타

나는 많은 솔루션을 시도했지만 아무도 나를 위해 일하지 않았습니다. XCode6 Beta 5를 사용하고 일부 솔루션은 예외를 제공합니다. 따라서 사전 정렬 작업 사본을 게시 할 수있는 사람입니다.


let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]

편집하다 :

위 코드에서 배열 된 배열에는 키만 포함되어 사전에 값을 검색해야합니다. 그러나 (키, 값) 쌍 'Dictionary'이기도하며 'CollectionType'전역 'sorted'함수를 사용하여 다음과 같이 키와 값을 모두 포함하는 배열 된 배열을 얻을 수 있습니다 .

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]

EDIT2 : 월간 변화하는 Swift 구문은 현재 선호합니다.

let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]

전역 sorted은 더 이상 사용되지 않습니다.


스위프트 2.0

Ivica M의 답변 업데이트 버전 :

let wordDict = [
     "A" : [1, 2],
     "Z" : [3, 4],
     "D" : [5, 6]
]

let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)") // 

스위프트 3

wordDict.sorted(by: { $0.0 < $1.0 })

주의 :

결과 배열이 사전이 아니라는 사실에 놀랐습니다. 사전은 정렬 할 수 없습니다 ! 결과 데이터 유형은 @Ivica의 답변과 배열 된 배열입니다.


키와 키 정렬 순서로 값을 반복 순서로 정렬합니다.

let d = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
    println("\(k):\(v)")
}

4에서는 더 똑똑하게 있습니다.

let d = [ 1 : "hello", 2 : "bye", -1 : "foo" ]
d = [Int : String](uniqueKeysWithValues: d.sorted{ $0.key < $1.key })

간단히 말해서 위의 모든 것을 시도해 보았습니다.

let sorted = dictionary.sorted { $0.key < $1.key }
let keysArraySorted = Array(sorted.map({ $0.key }))
let valuesArraySorted = Array(sorted.map({ $0.value }))


Swift 3의 경우 다음 정렬은 키로 정렬 된 사전을 리턴합니다.

let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]

let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })

print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]

스위프트 4의 경우 다음이 나를 위해 일했습니다.

let dicNumArray = ["q":[1,2,3,4,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[00,88,66,542,321]]

let sortedDic = dicNumArray.sorted { (aDic, bDic) -> Bool in
    return aDic.key < bDic.key
}

iOS 9 및 xcode 7.3에서 "정렬 됨", 신속한 2.2는 불가능합니다. "정렬 됨"을 "정렬"로 변경하십시오.

let dictionary = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedKeysAndValues = Array(dictionary).sort({ $0.0 < $1.0 })
print(sortedKeysAndValues)

//sortedKeysAndValues = ["desert": 2.99, "main course": 10.99, "salad": 5.99]

Swift 3의 경우 다음이 저에게 성이며 Swift 2 구문은 효과가 없습니다.

// menu is a dictionary in this example

var menu = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]

let sortedDict = menu.sorted(by: <)

// without "by:" it does not work in Swift 3

스위프트 3이 정렬됩니다 (기준 : <)

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(by:<) // ["A", "D", "Z"]

이 사전 자체를 정렬하는 우아한 대안입니다.

스위프트 4 & 5 기준

let sortedKeys = myDict.keys.sorted()

for key in sortedKeys {
   // Ordered iteration over the dictionary
   let val = myDict[key]
}

참고 URL : https://stackoverflow.com/questions/25377177/sort-dictionary-by-keys

반응형