Dictionaries

From Coder Merlin
Revision as of 22:44, 23 January 2023 by Chukwuemeka-tinashe (talk | contribs) (→‎Loops)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Introduction[edit]

A dictionary is a data type that functions similarly to an array in that it holds multiple keyed values. A key feature of a dictionary is the ability to use nearly any data type as the key. For example, a dictionary can be used to store a collection of student GPAs keyed by their names:

[
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
]

Order Is NOT Preserved[edit]

It's important to note that the order of keys and values will not necessarily remain the same. This can be seen by running the examples below, in which the output will not match up to the order in the definition.

Defining Dictionaries In Swift[edit]

Defining a dictionary in Swift has a similar syntax to defining arrays.

Empty Dictionary[edit]

To initialize an empty dictionary, the syntax is an opening bracket [, followed by the data type for the key (e.g. String), followed by a colon :, then the data type for the values (e.g. Double), then a closing bracket ] and a pair of parenthesis:

var dict = [String:Double]()

With Pre-defined Values[edit]

Setting up a dictionary with pre-defined values is also similar to the same definition with an array:

var dict = [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
]

Types[edit]

When you would like to accept a dictionary as a parameter to a function, you need to specify the type of key and value:

func prettyPrint(dict: [String:Double]) {
...
}

Keys[edit]

As previously mentioned, a dictionary can have keys of nearly any data type. Working with indexes is also extremely similar to working with arrays. For example, this would retrieve the value for the key "Potter":

dict["Potter"]

Similarly, this would either create or update the value keyed by "Potter" to a value of 3.5:

dict["Potter"] = 3.5

Loops[edit]

Also similar to arrays is how the values of a dictionary can be iterated through by using a for loop. Here is an example of using a for loop to create a prettyPrint function:


CoderMerlin™ Code Explorer: W0000 (1) 🟢


Notice that the for loop defines two variables for each iteration, key and value. If you try to only retrieve the value, as would ordinarily be done when iterating through an array, a tuple will be returned instead of the expected value:


CoderMerlin™ Code Explorer: W0000 (2) 🟢