Difference between revisions of "Dictionaries"

From Coder Merlin
m (Chukwuemeka-tinashe moved page W2273 Dictionaries to Dictionaries without leaving a redirect: Improved navigation)
Line 1: Line 1:
== Dictionaries ==
== Introduction ==
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''.
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''' are a type of '''hash table'''. A hash table is a data structure that 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).
<syntaxhighlight lang="swift">
[
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
]
</syntaxhighlight>


In 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.  
== 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.  


The structure of unordered lists in Swift is accomplished via unordered lists. Even if you make an error when entering a value into a dictionary, Swift will not allow it.
== Defining Dictionaries In Swift ==
Defining a dictionary in Swift has a similar syntax to defining arrays.  


A key is a number used to identify each item in a dictionary. A value is stored in the unique key, which may be referenced and looked up using the same key later. Unlike items in an array, values in a dictionary do not have to be kept in any particular order. When you need to find values based on their identifiers, use a dictionary instead of an array.
=== Empty Dictionary ===
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:


A key in a dictionary is unrestricted, although it must be unique within the dictionary.
<syntaxhighlight lang="swift">
var dict = [String:Double]()
</syntaxhighlight>


Because a variable receives a new dictionary as an assignment, it is always mutable, allowing you to add, remove, or modify its entries. If you assign a constant to a certain value, the dictionary becomes immutable and unchangeable in size and content.
=== With Pre-defined Values ===
Setting up a dictionary with pre-defined values is also similar to the same definition with an array:


== Curriculum ==
<syntaxhighlight lang="swift">
{{MerlinCurriculumData|{{ROOTPAGENAME}}}}
var dict = [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
]
</syntaxhighlight>


==Creating Dictionaries in Swift==
=== 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:


Swift allows you to create an empty dictionary of a specific type.
<syntaxhighlight lang="swift">
func prettyPrint(dict: [String:Double]) {
...
}
</syntaxhighlight>


If you need an Int dictionary but aren't sure what the key should be, you may use a different syntax to create one with an empty key of type Int and string values.
== 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">
<syntaxhighlight lang="swift">
//Basic syntax
dict["Potter"]
var myDictionary = [key: value]()
</syntaxhighlight>
 
Similarly, this would either create or update the value keyed by "Potter" to a value of 3.5:


//Example of dictionary creation
<syntaxhighlight lang="swift">
var myDictionary:[Int:String] = [1:"First", 2:"Second", 3:"Third"]
dict["Potter"] = 3.5
</syntaxhighlight>
</syntaxhighlight>


==Accessing Elements in Dictionaries==
== Loops ==
The subscript syntax may be used to access a value from a dictionary, as follows:  -> You may access a value from a dictionary using subscript syntax by entering the key of the desired item inside square brackets right after the name of the dictionary.
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
{{CodeExplorer
|exerciseID=1
|exerciseID=1
|height=150
|mode=swift
|mode=swift
|height=300
|initialCode=
|initialCode=import Foundation
func prettyPrint(dict: [String:Double]) {
    print("[")


//Note: Even though we set the keys in order from 1 to 3, don't feel the need the set the first item as 0 the way it would be in an array.
    for (key, value) in dict {
var myDictionary:[Int:String] = [1:"First", 2:"Second", 3:"Third"]
        print("   \"\(key)\": \(value)")
var firstItem = myDictionary[1]
    }
var secondItem = myDictionary[2]
var thirdItem = myDictionary[3]


print( "The first item is  \(firstItem!)")
    print("]")
print( "The second item is \(secondItem!)")
}
print( "The third item is \(thirdItem!)")


prettyPrint(dict: [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
])
}}
}}


==Updating Elements in Dictionaries==
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:
You may use the updateValue(forKey:) method to add a current value to a given key in the dictionary. This method returns an optional element from the dictionary's value type.
 


{{CodeExplorer
{{CodeExplorer
|exerciseID=2
|exerciseID=2
|height=150
|mode=swift
|mode=swift
|height=300
|initialCode=
|initialCode=import Foundation
func prettyPrint(dict: [String:Double]) {
    print("[")


var myDictionary:[Int:String] = [1:"First", 2:"Second", 3:"Third"]
    for value in dict {
var firstItem = myDictionary[1]
        print("   \(value)")
var secondItem = myDictionary[2]
    }
var thirdItem = myDictionary[3]


print( "The first item is  \(firstItem!)")
    print("]")
print( "The second item is \(secondItem!)")
}
print( "The third item is \(thirdItem!)")
 
myDictionary.updateValue("Updated value", forKey: 1)
print("The first item is  \(firstItem!)")


prettyPrint(dict: [
    "Potter": 4.0,
    "Bob": 1.2,
    "Merlin": 2.5,
    "Tim": 3.0
])
}}
}}
==Removing Key-Value Pairs from a Dictionary==
To remove a key-value pair from a dictionary, you may use the removeValueForKey() function. If the pair exists, it is deleted and the value returned; otherwise, nil is returned. Here's an example that shows how to use it:
{{CodeExplorer
|exerciseID=3
|mode=swift
|height=300
|initialCode=import Foundation
//Note: Even though we set the keys in order from 1 to 3, don't feel the need the set the first item as 0 the way it would be in an array.
var myDictionary:[Int:String] = [1:"First", 2:"Second", 3:"Third"]
var firstItem = myDictionary[1]
var secondItem = myDictionary[2]
var thirdItem = myDictionary[3]
print( "The first item is  \(firstItem!)")
print( "The second item is \(secondItem!)")
print( "The third item is \(thirdItem!)")
myDictionary.removeValue(forKey: 1)
print( "The first item is  \(firstItem!)")
}}
==Conclusion==
Dictionaries are very helpful when programming in Swift because they provide a quick way to access data. However, they also have some pitfalls that programmers should be aware of.
First, the implementation of a dictionary leaves values unguarded to some extent and programmers should take precautions against this.
Second, programmers should avoid retrieving data from an uninitialized or partially initialized dictionary as this can lead to unexpected behavior.
Third, programmers should be aware that accessing a key in a dictionary is ordered which means it will not be as fast as other collection types such as arrays.
Fourth, if dictionaries are used extensively throughout an app then those applications may suffer from slow performance due to those large amounts of allocations occurring on the heap.
Finally, one thing that I haven't mentioned much in this post but is worth mentioning is how using let generally affects performance because it prevents variables and constants from being put into the microprocessor's cache (the small amount of memory that is much faster than the main memory).

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