Dictionaries

Intermediate Julia

Anthony Markham

Quantitative Developer

Dictionaries - introduction

  • A collection of 'key-value' pairs.
  • Each value can be accessed using the corresponding key.
  • Mixed data types are allowed.
Intermediate Julia

Dictionaries - why are they useful?

  • Access values using a key, far more intuitive
stock = ["AAPL", 131.86, 100000]
println(stock[1])
AAPL
# Dictionary definition
stock = Dict("ticker" => "AAPL", "price" => 131.86)
println(stock["ticker"])
AAPL
Intermediate Julia

Dictionaries - untyped

  • Dict keyword to define a dictionary
  • Key => value
  • Separate key/value pairs with a comma
stock = Dict("ticker" => "AAPL", "price" => 131.86)
Dict{String, Any} with 2 entries:
  "ticker" => "AAPL"
  "price"  => 131.86
  • Note the data types are mixed and not pre-defined.
Intermediate Julia

Dictionaries - typed

  • Typed dictionaries force a key or value to be a certain data type.
stock_typed = Dict{String, Integer}("ticker" => "AAPL", "price" => 131.86)
MethodError: Cannot `convert` an object of type String to an object of type Integer
stock_typed = Dict{String, Any}("ticker" => "AAPL", "age" => 131.86)
Dict{String, Any} with 2 entries:
  "ticker" => "AAPL"
  "age"    => 131.86
Intermediate Julia

Dictionaries - iteration

  • Iteration is similar to other data structures that we are familiar with.
stock = Dict("ticker" => "AAPL", "price" => 131.86)
for i in stock
    println(i)
end
Pair{String, Any}("ticker", "AAPL")
Pair{String, Any}("price", 131.86)
Intermediate Julia

Dictionaries - iteration over keys and values

  • keys() and values() return the keys and values of a dictionary.
for i in keys(stock)
    println(i)
end
ticker
price
Intermediate Julia

Dictionaries - iteration via tuple unpacking

  • Tuple unpacking the keys and values is another way to iterate over a dictionary.
for (ticker, price) in stock
    println(ticker, " ", price)
end
ticker AAPL
price 131.86
Intermediate Julia

Dictionaries - get()

  • Use get() to get the value for a given key.
get(dictionary_name, dictionary_key, default_value)
  • The final argument is the default value, the return value if the key is not found.
stock = Dict("ticker" => "AAPL", "price" => 131.86)
println(get(stock, "ticker", "Key not found."))
AAPL
  • If we do not specify the default value argument and the key is not found, we get an error.
Intermediate Julia

Dictionaries - modification

  • We can add new keys, modify existing values, and delete keys.
# Add a new key
stock["volume"] = 62128300
println(stock)
Dict{String, Any}("ticker" => "AAPL", "price" => 131.86, "volume" => 62128300)
# Modify an existing value
stock["price"] = 125.27
println(stock)
Dict{String, Any}("ticker" => "AAPL", "price" => 125.27, "volume" => 62128300)
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...