Sorting a Dictionary Doesn’t Make Sense

Photo by Rachel on Unsplash

Prerequisites

Terminology

The video

The Dictionary

I want to order a Dictionary

Photo by CDC on Unsplash
let names = [“Arjun”, “Tisha”, “Zaara”,”Bob”, “Kasia”, “Natalia”, “Colin”, “Noah”, “Liya”, “Sergey”, “Kasia”, “Natalia”, “Colin”, “Noah”, “Liya”, “Sergey”, “Noah”, “Liya”]
var dictionary: [String: Int] = [:]
for name in names {
dictionary[name, default: 0] += 1
}
[“Noah”: 3, “Liya”: 3, “Tisha”: 1, “Arjun”: 1, “Zaara”: 1, “Sergey”: 2, “Natalia”: 2, “Colin”: 2, “Bob”: 1, “Kasia”: 2]

I can’t order a dictionary. What am I to do?

dictionary.sorted(by: { $0.value > $1.value })
[(key: “Noah”, value: 3), (key: “Liya”, value: 3), (key: “Sergey”, value: 2), (key: “Kasia”, value: 2), (key: “Colin”, value: 2), (key: “Natalia”, value: 2), (key: “Arjun”, value: 1), (key: “Bob”, value: 1), (key: “Tisha”, value: 1), (key: “Zaara”, value: 1)]
let sortedDictionary: [Dictionary<String, Int>.Element] = dictionary.sorted(by: { $0.value > $1.value })

A Dictionary.Element ?

sortedDictionary[“Colin”]

Conclusion

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store