Menu
CoddyTech

Dictionaries and Missing Keys

Lesson 21 of 48 in Coddy's Swift for Python Developers course.

Python dictionary subscripting raises KeyError when a key is absent; get can return a fallback instead. Swift dictionary subscripting returns an optional. Assigning nil through that subscript removes an entry.

Swift dictionaries are value types with one key type and one value type. For a fallback read, use ?? or the defaulted subscript. Keys must be hashable. Do not rely on dictionary traversal order for a required sorted report: sort keys explicitly. Python insertion order does not transfer to Swift dictionary iteration.

The example removes a configuration setting and reads a missing one. The task counts repeated words; dictionary lookup and update provide the building blocks, while sorting determines its report order.

Complete Python comparison program:

settings = {"font": 14, "gap": 2}
del settings["gap"]
print(settings.get("gap", 8))
print(len(settings))

Complete Swift comparison program, compiled from these files:

main.swift

var settings = ["font": 14, "gap": 2]
settings["gap"] = nil
print(settings["gap"] ?? 8)
print(settings.count)
challenge icon

Challenge

Easy

Implement frequencies(_:): count exact words. Input has 0 through 50 lowercase ASCII words, each 1 through 15 letters. Output word:count entries in ascending word order separated by spaces, or a blank line.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return frequencies(["oak","elm","oak"] ) == ["oak":2,"elm":1] && frequencies([]).isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

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

All lessons in Swift for Python Developers

Practice on your own: Swift playground