Leave a rating/review
Notes: 30. Challenge: Dictionaries
Update Notes: The student materials have been reviewed and are updated as of October 2021.
It’s time for your next challenge! You can find the challenge in the “04 - Challenge - Dictionaries” page of the playground you’ve been using, or you can download a new one from the resources for this video. Open it up, and try solving the challenge questions on your own, then keep watching to compare your work to mine. Good luck!
OK! You need to create a dictionary as a variable, and initialize it with the keys below. I’ll start with var chris, as the dictionary name, and then start creating key value pairs here:
var chris = [
"name": "Chris",
"profession": "Video Tutorialist",
"country": "Canada",
"city": "Halifax"
]
Now that your dictionary has been created, it’s time to modify things. I have made the bold decision to move to Cleveland, Ohio, USA. So I need to update my information to match.
First, I’ll update the country to USA:
chris["country"] = "USA"
Then, I’ll update my city to Cleveland:
chris["city"] = "Cleveland"
Now, I need to add a new key and value to this dictionary to store the state of Ohio. Now, I don’t need to do anything special here, because adding a new key-value pair looks just like updating an existing key and value:
chris["state"] = "Ohio"
Done!
Plans have changed again, and I’ve decided to become a digital nomad with no fixed address in the USA, so I have to remove the city and state from my information. I first need to remove the city key-value pair. I’ll use the removeValue method for that one, and specify this is forKey “city”:
chris.removeValue(forKey: "city")
Now, I need to use a different strategy to remove the “state” key value pair. Remember that a dictionary can’t store nil values or keys, so if I simply set the state key to nil, which that removes it from the dictionary as well.
chris["state"] = nil
Now that I’ve cleaned up my information for my life as a digital nomad, I want to iterate over the elements in the dictionary and print them out. So I’ll use a for loop, and operate on each key-value tuple in my chris dictionary:
for (key, value) in chris {
And now I’ll print out each pair inside the loop:
print("\(key): \(value)")
You’ll note that the order in which the keys-value pairs are printed out isn’t always the same order you defined them, and that’s because dictionaries are unordered collections.
You’ve learned quite a bit about dictionaries; in the next video, you’ll learn about another powerful collection called Sets, and how you can use them to perform comparative operations against other sets. I’ll see you there!