Learn
Dictionaries
Iterating through a Dictionary

We can use loops to iterate through all of the elements of a dictionary!

This is useful when we want to go through each individual key-value pair in a dictionary. For example, if we were the owners of a store, we may want to check the stock for every item we sell.

If we wanted to loop through every key and value in a dictionary using a for-in loop, the syntax would look as follows:

for (keyHolder, valueHolder) in dictionaryName {
  // Body of loop
}

For our placeholder, since dictionaries have both keys and values, we group them together in parentheses () and separate them by a comma.

Having more two or more values wrapped in parentheses () and separated by commas , is called a tuple. To learn more about tuples, check out Swift’s Documentation.

Let’s create a dictionary that store the names and grades of individual students in a class. If we want to view each student name and their grade, we would use the following code:

var classGrades = [ "Raymond": 100, "Rosa": 82, "Jake": 73, "Terry": 90 ] for (name, grade) in classGrades { print("\(name) has a grade of \(grade)") }

If we ran this code, we’d get something like the following output:

Rosa has a grade of 82 Raymond has a grade of 100 Jake has a grade of 73 Terry has a grade of 90

Instructions

1.

In GreekMythology.swift, iterate through the keys and values of the dictionary mythology using a for-in loop.

  • Name the key placeholder greekName.

  • Name the value placeholder romanName.

You can leave the body of the loop empty for now. You will see two warnings in the terminal on the right, but it will go away in the next step when we add code into the body of the loop.

2.

In the body of the loop, use print() to output the following statement:

[greekName] is also known as [romanName]

In the print() statement, use string interpolation to output the actual values of greekName and romanName.

Folder Icon

Take this course for free

Already have an account?