字典(Dictionaries)

Julia 中級

Anthony Markham

Quantitative Developer

字典 - 介紹

  • 「鍵-值」配對的集合。
  • 以對應的鍵存取值。
  • 可混合不同資料型別。
Julia 中級

字典 - 為何實用?

  • 用鍵存取值,更直覺。
stock = ["AAPL", 131.86, 100000]
println(stock[1])
AAPL
# Dictionary 定義
stock = Dict("ticker" => "AAPL", "price" => 131.86)
println(stock["ticker"])
AAPL
Julia 中級

字典 - 未標註型別

  • 使用 Dict 關鍵字建立字典。
  • 鍵 => 值。
  • 以逗號分隔每組鍵/值。
stock = Dict("ticker" => "AAPL", "price" => 131.86)
Dict{String, Any} with 2 entries:
  "ticker" => "AAPL"
  "price"  => 131.86
  • 注意可混合型別,且不需預先定義。
Julia 中級

字典 - 標註型別

  • 加上型別參數可限制鍵或值的資料型別。
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
Julia 中級

字典 - 迭代

  • 走訪(迭代)方式與常見資料結構相似。
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)
Julia 中級

字典 - 走訪鍵與值

  • keys()values() 會回傳字典的鍵與值。
for i in keys(stock)
    println(i)
end
ticker
price
Julia 中級

字典 - 以 tuple 拆解迭代

  • 也可用 tuple 拆解鍵與值來迭代字典。
for (ticker, price) in stock
    println(ticker, " ", price)
end
ticker AAPL
price 131.86
Julia 中級

字典 - get()

  • 使用 get() 以鍵取得值。
get(dictionary_name, dictionary_key, default_value)
  • 最後一個參數是預設值;若找不到鍵就回傳它。
stock = Dict("ticker" => "AAPL", "price" => 131.86)
println(get(stock, "ticker", "Key not found."))
AAPL
  • 若未提供預設值且找不到鍵,會出錯。
Julia 中級

字典 - 修改

  • 你可以新增鍵、修改現有值、刪除鍵。
# 新增鍵
stock["volume"] = 62128300
println(stock)
Dict{String, Any}("ticker" => "AAPL", "price" => 131.86, "volume" => 62128300)
# 修改值
stock["price"] = 125.27
println(stock)
Dict{String, Any}("ticker" => "AAPL", "price" => 125.27, "volume" => 62128300)
Julia 中級

一起來練習吧!

Julia 中級

Preparing Video For Download...