Menu
Coddy logo textTech

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 icon

Challenge

Easy

The scores dictionary maps student names to Int scores. Print:

  1. Every entry as <name>: <score>, sorted by name alphabetically, one per line
  2. Sum: <total> across all values (use .values and reduce)
  3. Above 70: <count> where count is how many entries have a score strictly greater than 70

For the default dictionary, the output is:

Alice: 85
Bob: 60
Cara: 90
Dan: 72
Sum: 307
Above 70: 3

Cheat 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 values

Try 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow