๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“Œ Language/Swift

[Swift] ๋”•์…”๋„ˆ๋ฆฌ ๋ฐธ๋ฅ˜๊ฐ’์œผ๋กœ ํ‚ค๊ฐ’ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ(Sort Dictionary keys by values)

by Fomagran ๐Ÿ’ป 2020. 8. 25.
728x90
๋ฐ˜์‘ํ˜•

ํ‰์†Œ์— ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•˜๋ฉด์„œ ๋ฐธ๋ฅ˜๊ฐ’์œผ๋กœ ํ‚ค๊ฐ’์„ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•ด์•ผ ํ•  ๋•Œ๊ฐ€ ์ •๋ง ๋งŽ์•˜์Šต๋‹ˆ๋‹ค.

๊ทธ๋ž˜์„œ ์—ด์‹ฌํžˆ ๊ตฌ๊ธ€๋ง ํ•ด๋ณธ ๊ฒฐ๊ณผ ๋ฐฉ๋ฒ•์„ ์ฐพ๊ฒŒ๋˜์–ด ์ •๋ฆฌ๋ฅผ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋จผ์ € ๋”•์…”๋„ˆ๋ฆฌ ์•ˆ์˜ ๊ฐ’์€ [์˜ํ™”์ด๋ฆ„:ํ‰์ ]๋กœ ๋งŒ๋“ค์–ด ์ฃผ๊ณ  ํ‰์  ์ˆœ์œผ๋กœ ์˜ํ™”๋ฅผ ์ •๋ ฌํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

์˜ํ™”๋Š”

์งฑ๊ตฌ๋Š”๋ชป๋ง๋ ค,๋‹ค๋งŒ์•…์—์„œ๊ตฌํ•˜์†Œ์„œ,๊ฐ•์ฒ ๋น„2,์˜ค์ผ€์ด๋งˆ๋‹ด,๋‚˜์˜์†Œ๋…€์‹œ๋Œ€ ์ด๋ ‡๊ฒŒ 5๊ฐ€์ง€๋กœ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ฃผ๊ณ 

=> let movies = ["์งฑ๊ตฌ๋Š”๋ชป๋ง๋ ค","๋‹ค๋งŒ์•…์—์„œ๊ตฌํ•˜์†Œ์„œ","๊ฐ•์ฒ ๋น„2","์˜ค์ผ€์ด๋งˆ๋‹ด","๋‚˜์˜์†Œ๋…€์‹œ๋Œ€"]

 

ํ‰์ ์€

๊ฐ๊ฐ 9.40,8.62,8.04,8.18,9.30 8์›” 25์ผ ๊ธฐ์ค€ ๋„ค์ด๋ฒ„ ํ‰์ ์œผ๋กœ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์ฃผ๊ฒ ์Šต๋‹ˆ๋‹ค.

=> let rates = [9.40,8.62,8.04,8.18,9.30]

์˜ํ™”๋ฅผ ํ‚ค๊ฐ’์œผ๋กœ ํ‰์ ์„ ๋ฐธ๋ฅ˜๊ฐ’์œผ๋กœ ํ•ด์„œ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

=> var dictionary = [String:Double]()

for i in 0..<movies.count {

    dictionary[movies[i]] = rates[i]

}

 

๋ฐธ๋ฅ˜๊ฐ’์ด ํฐ ์ˆœ์„œ๋Œ€๋กœ ๋”•์…”๋„ˆ๋ฆฌ์•ˆ์˜ ๊ฐ’๋“ค์„ ์ •๋ ฌํ•ด์ฃผ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

=> let sortedDitionary = dictionary.sorted { $0.1 > $1.1 }

 

๋งˆ์ง€๋ง‰์œผ๋กœ ์ •๋ ฌ๋œ ๋”•์…”๋„ˆ๋ฆฌ์•ˆ์˜ ํ‚ค๊ฐ’์„ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•ด์ฃผ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

=> for i in 0..<sortedDitionary.count {

    print("\(i+1).\(sortedDitionary[i].key)")

}

์•„๋ž˜์™€ ๊ฐ™์ด ํ‰์  ์ˆœ์œ„๋Œ€๋กœ ์˜ํ™”์ด๋ฆ„์ด ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ „์ฒด ์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Foundation

let movies = ["์งฑ๊ตฌ๋Š”๋ชป๋ง๋ ค","๋‹ค๋งŒ์•…์—์„œ๊ตฌํ•˜์†Œ์„œ","๊ฐ•์ฒ ๋น„2","์˜ค์ผ€์ด๋งˆ๋‹ด","๋‚˜์˜์†Œ๋…€์‹œ๋Œ€"]
let rates = [9.40,8.62,8.04,8.18,9.30]
var dictionary = [String:Double]()

for i in 0..<movies.count {
    dictionary[movies[i]] = rates[i]
}
 
let sortedDitionary = dictionary.sorted { $0.1 > $1.1 }
 
for i in 0..<sortedDitionary.count {
    print("\(i+1).\(sortedDitionary[i].key)")
}

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€