TExcelTAD
Home › Julia › Julia Dictionaries

Julia Dictionaries

A dictionary (Dict) maps keys to values. Looking up a value by its key is fast no matter how large the dictionary is, which makes Dict ideal for counting, caching and lookup tables.

julia · try it yourself
capitals = Dict("France" => "Paris", "Japan" => "Tokyo", "Peru" => "Lima")
println(capitals["Japan"])
println(length(capitals))
println(typeof(capitals))

capitals["Kenya"] = "Nairobi"     # add a new pair
capitals["Peru"] = "LIMA"         # overwrite an existing key
println(capitals["Peru"], " ", length(capitals))
Tokyo
3
Dict{String, String}
LIMA 4

A Dict is created from key => value pairs. Its type records both the key and value types. Keys must be unique: assigning to an existing key replaces its value.

Safe lookups

Reading a missing key with d[key] throws a KeyError. Check first, or provide a default:

julia · try it yourself
stock = Dict("apple" => 12, "pear" => 0)
println(haskey(stock, "kiwi"))
println(get(stock, "kiwi", 0))
println("apple" in keys(stock))
try
    stock["kiwi"]
catch e
    println(sprint(showerror, e))
end

println(get!(stock, "kiwi", 5))   # inserts the default if missing
println(stock["kiwi"])
false
0
true
KeyError: key "kiwi" not found
5
5

Removing entries

julia · try it yourself
d = Dict(:a => 1, :b => 2, :c => 3)
println(pop!(d, :a))
delete!(d, :b)
println(d)
println(pop!(d, :zzz, "default"))
empty!(d)
println(isempty(d))
1
Dict(:c => 3)
default
true

Iterating

Iterating a dictionary gives key => value pairs. The order is not guaranteed, so sort the keys when you need a stable order:

julia · try it yourself
ages = Dict("Zoe" => 31, "Adam" => 45, "Mei" => 28)
for name in sort(collect(keys(ages)))
    println(name, " is ", ages[name])
end
println(sum(values(ages)))

for (name, age) in sort(collect(ages), by = p -> p.second)
    println(age, " ", name)
end
Adam is 45
Mei is 28
Zoe is 31
104
28 Mei
31 Zoe
45 Adam

Tip: Need insertion order? Use OrderedDict from the OrderedCollections.jl package, or keep a separate vector of keys.

Counting with a dictionary

A classic use: count how often each word appears.

julia · try it yourself
text = "the cat and the dog and the bird"
counts = Dict{String, Int}()
for word in split(text)
    counts[word] = get(counts, word, 0) + 1
end
for (word, n) in sort(collect(counts), by = p -> (-p.second, p.first))
    println(rpad(word, 5), n)
end
the  3
and  2
bird 1
cat  1
dog  1

Dict{String, Int}() creates an empty dictionary with fixed key and value types. Sorting by (-count, word) orders by count descending, then alphabetically.

Merging and transforming

julia · try it yourself
defaults = Dict("color" => "blue", "size" => 10)
user = Dict("size" => 14)
config = merge(defaults, user)          # later dictionaries win
println(config["color"], " ", config["size"])

totals = mergewith(+, Dict("a" => 1, "b" => 2), Dict("b" => 10, "c" => 5))
println(sort(collect(totals)))

squares = Dict(n => n^2 for n in 1:4)   # dictionary comprehension
println(squares[3])
inverse = Dict(v => k for (k, v) in squares)
println(inverse[16])
blue 14
["a" => 1, "b" => 12, "c" => 5]
9
4

Keys can be any value that can be hashed: strings, numbers, symbols, tuples. Symbols such as :name are a common, efficient choice for fixed keys.

Test yourself

What does get(d, "x", 0) return when "x" is not a key of d?

  1. nothing
  2. 0
  3. a KeyError
  4. "x"

What happens when you assign to a key that already exists?

  1. A duplicate entry is added
  2. The old value is replaced
  3. An error is thrown
  4. The assignment is ignored

In which order does for (k, v) in d visit a Dict?

  1. Insertion order
  2. Sorted by key
  3. An unspecified order
  4. Sorted by value