Skip to content
AgileLogics
6 min read

Dictionaries and Sets

Prerequisites: Arrays

A dictionary (Dict) maps keys to values. Each entry is written as a pair key => value:

ages = Dict("Ada" => 36, "Alan" => 41)
ages["Grace"] = 85
println(ages["Ada"])
println(haskey(ages, "Alan"), " ", haskey(ages, "Bob"))
println(get(ages, "Bob", 0))
println(length(ages))
delete!(ages, "Alan")
for name in sort(collect(keys(ages)))
    println(name, " => ", ages[name])
end
36
true false
0
3
Ada => 36
Grace => 85
  • d[key] reads (and throws a KeyError if the key is missing); get(d, key, default) is the safe version.
  • haskey checks for a key, delete! removes one.
  • keys(d) and values(d) give the keys and values. A Dict has no guaranteed order, so sort the keys when order matters.

Counting things

text = "the cat and the hat and the bat"
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[2], p[1]))
    println(word, ": ", n)
end
the: 3
and: 2
bat: 1
cat: 1
hat: 1
  • Dict{String,Int}() makes an empty dictionary with fixed key and value types.
  • collect(counts) gives a vector of pairs, which we sort by count (descending) and then by word.

get! for grouping

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = Dict{Char,Vector{String}}()
for w in words
    push!(get!(groups, w[1], String[]), w)
end
for k in sort(collect(keys(groups)))
    println(k, ": ", groups[k])
end
a: ["apple", "avocado"]
b: ["banana", "blueberry"]
c: ["cherry"]

get!(d, key, default) returns the value, storing the default first if the key is missing.

Sets

A Set holds unique values and makes membership tests fast:

a = Set([1, 2, 3, 3, 3])
b = Set([3, 4])
println(length(a), " ", 2 in a)
println(sort(collect(union(a, b))))
println(intersect(a, b))
println(sort(collect(setdiff(a, b))))
push!(a, 10)
println(10 ∈ a, " ", issubset(Set([1, 2]), a))
3 true
[1, 2, 3, 4]
Set([3])
[1, 2]
true true

Practice

Given a vector of votes ["red", "blue", "red", "green", "blue", "red"], count the votes per color with a Dict and print the winner.

Show solution
votes = ["red", "blue", "red", "green", "blue", "red"]
tally = Dict{String,Int}()
for v in votes
    tally[v] = get(tally, v, 0) + 1
end
winner = argmax(tally)
println("winner: $winner with $(tally[winner]) votes")
winner: red with 3 votes

argmax on a dictionary returns the key with the largest value.