"Dictionary subscripting" is the practice of using a "subscript", dict[key] with [ and ], in order to get or update the value associated with a key in a dictionary:
// Get the optional value, if any (maybe there is no value associated with the key)
let value = dict[key]
// Process the value, if any
if let value = dict[key] {
print(value)
} else {
print("no value")
}
// Set the value
dict[key] = ...
In your case, the code snippets below show you how "dictionary subscripting" helps solving your problem.
First version: iterate input pairs, and update the output dictionary with subscripting as described above
var actualOutput: [Int: [Int]] = [:]
for (left, right) in input {
if let elements = actualOutput[left] {
actualOutput[left] = elements + [right]
} else {
actualOutput[left] = [right]
}
}
print("OUTSIDE", actualOutput)
Second version: modify accumulated elements in place, with append(_:).
var actualOutput: [Int: [Int]] = [:]
for (left, right) in input {
if var elements = actualOutput[left] {
elements.append(right)
actualOutput[left] = elements
} else {
actualOutput[left] = [right]
}
}
print("OUTSIDE", actualOutput)
Third version: modify accumulated elements right inside the output dictionary, with subscript(_:default:).
This third version is my favorite. It is very readable, and will please both beginners and experienced programmers:
var actualOutput: [Int: [Int]] = [:]
for (left, right) in input {
actualOutput[left, default: []].append(right)
}
print("OUTSIDE", actualOutput)
Fourth version: replace the for loop with the reduce standard library method. One advantage is that the actualOutput variable is no longer mutable (we can declare it as let).
let actualOutput: [Int: [Int]] = input.reduce(into: [:]) { output, tuple in
output[tuple.0, default: []].append(tuple.1)
}
print("OUTSIDE", actualOutput)
Some other readers will surely come up with other versions as well :-)