Iterating Dictionaries
Part of the Logic & Flow section of Coddy's Swift journey — lesson 15 of 56.
Iterating a dictionary with for hands you both halves of each pair as a tuple:
let prices = ["apple": 1, "bread": 3, "milk": 4]
for (item, price) in prices {
print("\(item) costs \(price)")
}Iteration order is not guaranteed. Run the loop twice and you might see entries in a different order. When the ordering matters, sort first:
for (item, price) in prices.sorted(by: { $0.key < $1.key }) {
print("\(item): \(price)")
}The expression inside sorted(by:) is a closure: it compares two pairs ($0 and $1) by their key property. Closures get a chapter of their own later, for now treat this as a recipe for sorting a dictionary.
Two more useful properties: .keys and .values give you the keys-only or values-only collection.
Challenge
EasyThe scores dictionary maps student names to Int scores. Print:
- Every entry as
<name>: <score>, sorted by name alphabetically, one per line Sum: <total>across all values (use.valuesandreduce)Above 70: <count>wherecountis how many entries have a score strictly greater than70
For the default dictionary, the output is:
Alice: 85
Bob: 60
Cara: 90
Dan: 72
Sum: 307
Above 70: 3Cheat sheet
Iterate a dictionary with for to get key-value tuples:
let prices = ["apple": 1, "bread": 3, "milk": 4]
for (item, price) in prices {
print("\(item) costs \(price)")
}Iteration order is not guaranteed. Sort first when order matters:
for (item, price) in prices.sorted(by: { $0.key < $1.key }) {
print("\(item): \(price)")
}Access keys or values only with .keys and .values:
prices.keys // collection of keys
prices.values // collection of valuesTry it yourself
let scores: [String: Int] = [
"Alice": 85, "Bob": 60, "Cara": 90, "Dan": 72
]
// TODO: print sorted entries; sum via reduce on .values; count > 70
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check3Dictionaries
Declaring DictionariesOptional LookupUpdating DictionariesIterating DictionariesGrouping ValuesRecap - Inventory