Difference between revisions of "Dictionaries"

From Coder Merlin
(Created page with "{{ComingSoon|Dictionaries}} == Dictionaries == Arrays are a collection type and enable us to quickly and easily access an element of the collection at a specific index, ident...")
 
(4 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{ComingSoon|Dictionaries}}
== Introduction ==
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:


== Dictionaries ==
<syntaxhighlight lang="swift">
Arrays are a collection type and enable us to quickly and easily access an element of the collection at a specific index, identified by an integer offset from the beginning of the collection. While arrays are very fast, they don’t provide us with the ability to quickly access an element given a ''key of arbitrary type''.
[
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
]
</syntaxhighlight>


'''Dictionaries''' are a type of '''hash table'''.  A hash table is a data structure which implements the abstract data type '''associative array'''. The hash table uses a '''hash function''' to compute an index into an array of slots at which the element can be found.  In a well-implemented algorithm, access to the element can occur in O(1).
== Order Is NOT Preserved ==
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.  


n some cases, a hash function may not produce unique values.  This is termed a '''collision'''.  Collisions need to be appropriately resolved in order to access the proper element.  
== Defining Dictionaries In Swift ==
Defining a dictionary in Swift has a similar syntax to defining arrays.  


<pre>
=== Empty Dictionary ===
var d = Dictionary<String, Int>()
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:
d[“Jack”] = 100
d[“Jill”] = 200


print(d[“Jill”]!)
<syntaxhighlight lang="swift">
</pre>
var dict = [String:Double]()
</syntaxhighlight>
 
=== With Pre-defined Values ===
Setting up a dictionary with pre-defined values is also similar to the same definition with an array:
 
<syntaxhighlight lang="swift">
var dict = [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
]
</syntaxhighlight>
 
=== Types ===
When you would like to accept a dictionary as a parameter to a function, you need to specify the type of key and value:
 
<syntaxhighlight lang="swift">
func prettyPrint(dict: [String:Double]) {
...
}
</syntaxhighlight>
 
== Keys ==
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":
 
<syntaxhighlight lang="swift">
dict["Potter"]
</syntaxhighlight>
 
Similarly, this would either create or update the value keyed by "Potter" to a value of 3.5:
 
<syntaxhighlight lang="swift">
dict["Potter"] = 3.5
</syntaxhighlight>
 
== Loops ==
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:
 
 
{{CodeExplorer
|exerciseID=1
|height=150
|mode=swift
|initialCode=
func prettyPrint(dict: [String:Double]) {
    print("[")
 
    for (key, value) in dict {
        print("    \"\(key)\": \(value)")
    }
 
    print("]")
}
 
prettyPrint(dict: [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
])
}}
 
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:
 
 
{{CodeExplorer
|exerciseID=2
|height=150
|mode=swift
|initialCode=
func prettyPrint(dict: [String:Double]) {
    print("[")
 
    for value in dict {
        print("    \(value)")
    }
 
    print("]")
}
 
prettyPrint(dict: [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
])
}}

Revision as of 21:14, 1 November 2021

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) 🟢