Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 40 ยท Collections

Dictionaries and Sets

Learn Julia dictionaries and sets: Dict creation, pairs, get, haskey, iteration order, union, intersect and setdiff, with runnable Python stand-ins.

When you need to look something up by name rather than by position, you use a dictionary. A Julia Dict maps keys to values: a word to a count, a user name to a record, a pair of coordinates to a tile. A Set is the related idea for membership only: a collection of distinct items where the question is "is this in here?". Both are hash-based, so lookup, insertion and deletion take roughly constant time even for millions of entries.

This lesson covers creating and updating dictionaries, the safe ways to read a missing key, iterating, the fact that Dict is not ordered, and the set operations union, intersect and setdiff. The Julia code is read-only on this site. Python's dict and set are close relatives, so the runnable examples use them, with the differences noted.

Creating a Dict

A dictionary is built from key => value pairs. The arrow creates a Pair, and the Dict constructor collects them.

JULIA
ages = Dict("Ada" => 36, "Linus" => 54, "Grace" => 85)

typeof(ages)        # Dict{String, Int64}
length(ages)        # 3
ages["Ada"]         # 36

empty = Dict{String, Int}()     # empty, with declared key and value types
scores = Dict(1 => "one", 2 => "two")

Julia infers the key and value types from the pairs, as with arrays, and declares them in the type. Declaring them yourself for an empty dictionary (Dict{String, Int}()) is important: a bare Dict() has type Dict{Any, Any}, which is slow and lets wrong types in unnoticed. Keys can be any type that supports hashing and ==, such as strings, numbers, symbols and tuples. Do not use a mutable array as a key and then change it.

Dictionaries can also be built from other collections:

JULIA
squares = Dict(n => n^2 for n in 1:4)    # a generator of pairs
Dict(zip(["a", "b", "c"], [1, 2, 3]))    # from two parallel lists

Reading a Dict safely

d[key] Fast, but a missing key is an error.
get(d, key, 0) Give a default for a missing key.
haskey(d, key) Ask first; returns true or false.
1 / 2

Reading, adding and removing

Indexing with a missing key raises a KeyError. Use get to supply a default, or haskey to test first.

JULIA
ages = Dict("Ada" => 36, "Linus" => 54)

ages["Ada"]                 # 36
ages["Zed"]                 # KeyError: key "Zed" not found
get(ages, "Zed", -1)        # -1, nothing is added
haskey(ages, "Ada")         # true
"Ada" in keys(ages)         # true

ages["Grace"] = 85          # adds a new key
ages["Ada"] = 37            # replaces an existing value
delete!(ages, "Linus")      # removes the key; no error if absent
pop!(ages, "Grace")         # removes and returns 85

There are two more helpers you will use all the time. get!(d, key, default) returns the value if the key exists, and otherwise stores the default and returns it. The block form is useful when the default is costly to create:

JULIA
groups = Dict{Int, Vector{String}}()

for word in ["pear", "fig", "plum", "kiwi", "apple"]
    push!(get!(groups, length(word), String[]), word)
end
# groups[4] == ["pear", "plum", "kiwi"], groups[3] == ["fig"], groups[5] == ["apple"]

Counting is the classic job for get:

JULIA
counts = Dict{String, Int}()
for w in split("the cat and the hat and the bat")
    counts[w] = get(counts, w, 0) + 1
end
counts["the"]       # 3
counts["and"]       # 2

Iterating

Looping over a dictionary yields pairs, which you can destructure. The functions keys, values and pairs give views onto the content without copying.

JULIA
prices = Dict("tea" => 3.5, "coffee" => 4.0, "cake" => 5.25)

for (item, price) in prices
    println(item, " costs ", price)
end

keys(prices)            # the keys (a view)
values(prices)          # the values
sum(values(prices))     # 12.75
collect(keys(prices))   # a real Vector of the keys
sort(collect(keys(prices)))   # ["cake", "coffee", "tea"]

[k for (k, v) in prices if v > 3.8]    # keys with a price over 3.8

Do not add or remove keys while looping over the same dictionary. Changing the values of existing keys is fine.

No guaranteed order

A Dict is hash-based, and the order in which keys, values and the for loop visit the entries is not defined. It may differ from the order you inserted them and from one Julia version to the next. So Dict("a" => 1, "b" => 2) could print the pairs in either order. When you need a stable order, sort the keys: for k in sort(collect(keys(d))). If you need insertion order itself, use OrderedDict from the OrderedCollections package (see Packages and Environments). In this respect Julia differs from Python 3.7 and later, where dictionaries remember insertion order.

Sets

A Set holds distinct values with no duplicates and no order. Construct it from any collection.

JULIA
a = Set([1, 2, 3, 3, 2])     # Set([1, 2, 3])
length(a)                    # 3
2 in a                       # true
7 โˆˆ a                        # false (โˆˆ is typed \in and Tab)

push!(a, 10)                 # add
delete!(a, 1)                # remove
empty_set = Set{Int}()

Adding something that is already present has no effect. Checking membership with in on a set is fast, while on a vector it scans the entire vector, so convert large lookup tables to sets first.

The usual mathematical operations are available as functions, and as operators for the common ones:

JULIA
a = Set([1, 2, 3, 4])
b = Set([3, 4, 5])

union(a, b)          # Set([1, 2, 3, 4, 5])      also  a โˆช b
intersect(a, b)      # Set([3, 4])               also  a โˆฉ b
setdiff(a, b)        # Set([1, 2])  in a but not in b
symdiff(a, b)        # Set([1, 2, 5])  in exactly one of them
issubset(Set([3]), a)    # true                  also  Set([3]) โІ a
isdisjoint(a, Set([9]))  # true

The same functions accept other collections too: unique(v) returns the distinct elements of a vector in order of first appearance, and union(v1, v2) on two vectors returns a vector without duplicates. A set is the right tool for membership questions, for removing duplicates, and for "which items are in both lists?".

Stand-ins you can run

Python's dict behaves like Julia's Dict except for two points: the insertion order is kept, and d.get(key, default) is a method instead of a function. The first example mirrors the read, update and counting patterns.

Python A dictionary tour: get, counts and groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second example covers sets. Python writes the operators |, &, - and ^ for union, intersection, difference and symmetric difference, which Julia spells โˆช, โˆฉ, setdiff and symdiff.

Python Set operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does d["missing"] do in Julia when the key is not in d?

    Indexing a missing key is an error. Use get(d, key, default) or haskey(d, key) to handle absent keys.
  2. 2. Which line counts occurrences of a word w in a Dict{String,Int} called counts?

    counts[w] += 1 fails for a key that is not there yet. get supplies the starting 0.
  3. 3. In what order does a Julia Dict iterate?

    Dict is hash-based and its order is unspecified. Use sort(collect(keys(d))) or an OrderedDict when order matters.
  4. 4. What is setdiff(Set([1, 2, 3]), Set([2, 3, 4]))?

    setdiff(a, b) keeps the elements of a that are not in b, which leaves 1.

Summary

  • Dict("k" => v, ...) maps keys to values; declare types for an empty one: Dict{String, Int}().
  • d[key] errors on a missing key; use get(d, key, default), haskey, and get! to read safely or fill in defaults.
  • d[key] = v adds or replaces, delete! and pop! remove, and merge combines dictionaries.
  • Iterating yields (key, value) pairs in no guaranteed order; sort the keys for a stable order.
  • Set stores distinct values with fast in checks; union, intersect, setdiff, symdiff and issubset do the set algebra.

Next: learn how Julia classifies values in The Type System.