ProgramGuru

Dictionaries: look up a value by key

Dictionaries: look up a value by key

A teacher wants to retrieve a mark by student name rather than by position. A Dictionary associates unique keys with values of a common type. Looking up an absent key returns an optional, which allows an explicit missing-student path.

What you’ll learn

  • Handle a dictionary lookup that may be absent.
  • Update or remove one key and choose deterministic report ordering.

Dictionaries: look up a value by key in the example

  1. Key

    A teacher wants to retrieve a mark by student name rather than by position.

    Key
  2. Lookup optional value

    Assigning a value to an existing key replaces its value; assigning nil through the subscript removes an entry.

    Lookup optional value
  3. Handle presence or absence

    Diya’s existing value becomes 85.

    Handle presence or absence
Diya’s existing value becomes 85. Noor is absent, so the comparison with nil is true. Sorting the keys produces a stable alphabetical display without claiming the dictionary stores them in that order.

How dictionaries: look up a value by key works

Assigning a value to an existing key replaces its value; assigning nil through the subscript removes an entry. Dictionary iteration order is not a promised report order. Sort keys when the displayed order matters. Keys must support Hashable so the collection can organize lookups.

Work through dictionaries: look up a value by key

Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.

Swift · complete program

var scores = ["Diya": 80, "Saira": 90]
scores["Diya"] = 85
print(scores["Diya"] ?? -1)
print(scores["Noor"] == nil)
print(scores.keys.sorted().joined(separator: ", "))

Expected output

85
true
Diya, Saira

Follow the execution

Diya’s existing value becomes 85. Noor is absent, so the comparison with nil is true. Sorting the keys produces a stable alphabetical display without claiming the dictionary stores them in that order.

Try this program in the Swift compiler. Paste the complete source above.

Practice: Dictionaries: look up a value by key

Your task: What happens if you assign scores["Saira"] = nil?

Swift · complete program

var scores = ["Diya": 80, "Saira": 90]
scores["Diya"] = 85
print(scores["Diya"] ?? -1)
print(scores["Noor"] == nil)
print(scores.keys.sorted().joined(separator: ", "))

Worked answer

Saira’s entry is removed. A later lookup returns nil, which must be handled separately from any actual score.

Choose keys that identify students

Names may not be unique in a real school. Use an appropriate student identifier as the key and retain the display name as data. Do not silently overwrite two different students merely because their names match.

Check your decision

What happens if you assign scores["Saira"] = nil?
Choose one answer. You can try again.

Answer and explanation

Saira’s entry is removed.

Saira’s entry is removed. A later lookup returns nil, which must be handled separately from any actual score.

Choose keys that identify students

Saira’s entry is removed. A later lookup returns nil, which must be handled separately from any actual score. Names may not be unique in a real school.

Further reading: official Swift language guide.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Sets and tuples solve different jobs →