Julia Dictionaries Guide — Dict, Sets, and Key-Value Data Structures
In this tutorial, you will learn about Julia Dictionaries Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Julia Dict is a Hash Table mapping keys to values with type parameters Dict{K,V}, supporting get with defaults, get! for insertion, merge for combining, and haskey/keys/values for collection access -- with Set for unique elements.
Creating Dictionaries
# Type-stable dictionary
d = Dict{String, Int}()
d["Alice"] = 30
d["Bob"] = 25
# Literal syntax
scores = Dict("Alice" => 95, "Bob" => 87, "Carol" => 92)
# From pairs
pairs = [("a", 1), ("b", 2)]
d = Dict(pairs)
# Type inference
d = Dict(:red => "#FF0000", :green => "#00FF00")
Accessing Values
scores = Dict("Alice" => 95, "Bob" => 87)
# Direct access
scores["Alice"] # 95
scores["Dave"] # KeyError!
# Safe access with default
get(scores, "Dave", 0) # 0 (default)
get(scores, "Alice", 0) # 95
# get! - insert default if missing
get!(scores, "Dave", 0) # returns 0, adds to dict
# Check existence
haskey(scores, "Alice") # true
in("Alice" => 95, scores) # true
Iteration and Manipulation
d = Dict("a" => 1, "b" => 2, "c" => 3)
# Keys and values
keys(d) # key iterator
values(d) # value iterator
collect(keys(d)) # ["a", "b", "c"]
# Iterate
for (k, v) in d
println("$k: $v")
end
# Merge
d2 = Dict("c" => 30, "d" => 40)
merge(d, d2) # later keys overwrite earlier
merge!(d, d2) # in-place merge
# Filter
filter(p -> last(p) > 1, d) # Dict("b" => 2, "c" => 3)
Sets
# Creating sets
s = Set{Int}()
push!(s, 1)
push!(s, 2)
push!(s, 3)
# From array
s = Set([1, 2, 3, 2, 1]) # Set([1, 2, 3])
# Set operations
union(Set([1, 2]), Set([2, 3])) # Set([1, 2, 3])
intersect(Set([1, 2, 3]), Set([2, 3, 4])) # Set([2, 3])
setdiff(Set([1, 2, 3]), Set([2])) # Set([1, 3])
# Membership
in(1, s) # true
1 in s # true (infix syntax)
Common Mistakes
1. KeyError on missing key
Accessing a missing key throws a KeyError. Use get(d, key, default) for safe access.
2. Mutable keys
Dict keys must be immutable (hashable). Numbers, strings, symbols are fine. Arrays or Dicts as keys are problematic.
3. Type instability
Dict() without type annotations creates an Any-type dict which is slower. Prefer Dict{String, Int}().
Practice Questions
1. How do you get a value with a default?
get(dict, key, default) returns the value or default if key doesn't exist.
2. How do you check if a key exists?
haskey(dict, key) returns true/false. Or test: key in keys(dict).
3. How do you create a Set from an array?
Set([1, 2, 3, 2, 1]) creates a Set with unique elements {1, 2, 3}.
FAQ
{{< faq question="Are Julia Dicts ordered?" >}} No, Dict elements are unordered. Use OrderedDict from DataStructures.jl for insertion-ordered dict. {{< /faq >}}
{{< faq question="How do I count occurrences?" >}}
Use counter = Dict{String, Int}(); for item in items; counter[item] = get!(counter, item, 0) + 1; end.
{{< /faq >}}
{{< faq question="What types can be dictionary keys?" >}} Immutable types: numbers, strings, symbols, tuples of immutable types. Mutable types (arrays, dicts) cannot be keys. {{< /faq >}}
What's Next
Now learn about modules in Julia.
| Topic | Description | Link |
|---|---|---|
| Modules | Module system | {{< ref "11-modules" >}} |
| File I/O | Reading and writing files | {{< ref "12-file-io" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro