Dictionaries

2.3. Dictionaries#

A dictionary is like an array, but more general. In an array, the indices have to be integers; in a dictionary they can be (almost) any type.

A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item. An example of constructing a dictionary is given below

classes = Dict("Introduction to Real Analysis" => 104, "Programming for Mathematical Applications" => 124 )
Dict{String, Int64} with 2 entries:
  "Programming for Mathematical Applications" => 124
  "Introduction to Real Analysis"             => 104

Here the keys are the Strings Introduction to Real Analysis and Programming for Mathematical Applications. If you would like to get the value a key is paired with, use the get(collection, key, default) function.

get(classes, "Programming for Mathematical Applications", "Class not found")
124

If the key is not found within the dictionary, the function will return the default value.

get(classes, "Introduction to Abstract Algebra", "Class not found")
"Class not found"

We can get values using bracket notation.

classes["Programming for Mathematical Applications"]
124

If you would like to insert a key-value mapping to the dictionary, use the push! function (just like arrays!).

push!(classes, "Introduction to Abstract Algebra" => 113)
Dict{String, Int64} with 3 entries:
  "Programming for Mathematical Applications" => 124
  "Introduction to Abstract Algebra"          => 113
  "Introduction to Real Analysis"             => 104

Dictionaries also allow you to directly edit the entries like arrays as follows:

classes["Introduction to Complex Analysis"] = 185
185

If you would like to remove a key-value mapping, use the delete!(collection, key) function

delete!(classes, "Introduction to Real Analysis")
Dict{String, Int64} with 3 entries:
  "Programming for Mathematical Applications" => 124
  "Introduction to Complex Analysis"          => 185
  "Introduction to Abstract Algebra"          => 113