Skip to Content
Learn
Dictionaries
Review

Great job! In this lesson, we went over the following concepts:

  • A dictionary is an unordered collection of key-value pairs.

  • A key is a unique identifier used to create, update, remove, or access an associated value.

  • We can create populated dictionaries using dictionary literals:

    var dictionaryName = [Key1: Value1, Key2: Value2]
  • An empty dictionary contains no key-values pairs. There are two methods of initializing an empty dictionary:

    // Initializer Syntax: var emptyInitializer = [KeyType: ValueType]() // Dictionary Literal Syntax: var emptyLiteral: [KeyType: ValueType] = [:]
  • We can add elements to a dictionary using subscript syntax:

    dictionaryName[NewKey] = NewValue
  • We can remove dictionary elements using .removeValue() or by setting a key value to nil.

    dictionaryName.removeValue(forKey: Key) dictionaryName[Key] = nil
  • We can remove all the values from a dictionary with .removeAll().

  • We can update the value of a key-value pair using subscript syntax or .updateValue():

    dictionaryName[Key] = NewValue dictionaryName.updateValue(NewValue, forKey: Key)
  • The .isEmpty property returns a boolean that equals true if a dictionary is empty.

  • The .count property returns the number of elements contained within a dictionary.

  • We can access a value using its key:

    dictionaryName[Key]
  • We can use for-in loops to iterate through the content of a dictionary:

    for (KeyHolder, ValueHolder) in dictionaryName { // Add body }
  • We can use the .keys property to access only the keys of a dictionary.

  • We can use the .values property to access only the values of a dictionary.

Instructions

Want to practice using dictionaries? Take a look at the following optional challenges!

  • Create a dictionary with the name of your favorite movie/tv show.
  • Populate the dictionary with the names of characters as keys and their actors as values.
  • Remove, add, and change key-value pairs.
  • Iterate through the dictionary to see all the characters and the actors who played them.

When you’re ready to continue, hit Next.

Folder Icon

Take this course for free

Already have an account?