Julia Dictionaries and Sets
In the previous chapters, we learned about Julia Arrays and Julia Tuples.
Arrays are a type of collection, and Julia also supports other types of collections, such as dictionaries and sets (unordered collection lists).
Dictionaries
A dictionary is a mutable container model that can store objects of any type.
Each key-value pair key=>value
in the dictionary is separated by =>
, and each pair is separated by a comma ,
. The entire dictionary is enclosed in curly braces {}
, as shown below:
Creating a Dictionary
Dict("key1" => value1, "key2" => value2, ..., "keyn" => valuen)
The following example creates a simple dictionary where the key "A" corresponds to the value 1, and the key "B" corresponds to the value 2:
Dict("A"=>1, "B"=>2)
Example
julia> D = Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia>
Creating a dictionary using a for loop:
Example
julia> first_dict = Dict(string(x) => sind(x) for x = 0:5:360)
Dict{String, Float64} with 73 entries:
"285" => -0.965926
"310" => -0.766044
"245" => -0.906308
"320" => -0.642788
"350" => -0.173648
"20" => 0.34202
"65" => 0.906308
"325" => -0.573576
"155" => 0.422618
"80" => 0.984808
"335" => -0.422618
"125" => 0.819152
"360" => 0.0
"75" => 0.965926
"110" => 0.939693
"185" => -0.0871557
"70" => 0.939693
"50" => 0.766044
"190" => -0.173648
⋮ => ⋮
Keys
Keys in a dictionary are unique. If we assign a value to an already existing key, we do not create a new one but modify the existing key.
Checking for a Key
We can use the haskey()
function to check if a dictionary contains a specified key:
Example
julia> D = Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia> haskey(first_dict, "A")
false
julia> haskey(D, "A")
true
julia> haskey(D, "Z")
false
We can also use the in()
function to check if a dictionary contains a key/value pair:
Example
julia> D = Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia> in(("A" => 1), D)
true
julia> in(("X" => 220), first_dict)
false
Adding a Key/Value Pair
We can add a new key/value pair to an existing dictionary as follows:
Example
julia> D = Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia> D["C"] = 3
3
julia> D
Dict{String, Int64} with 3 entries:
"B" => 2
"A" => 1
"C" => 3
Deleting a Key/Value Pair
We can use the delete!()
function to delete a key from an existing dictionary:
Example
julia> delete!(D, "C")
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
Getting All Keys in the Dictionary
We can use the keys()
function to get all the keys in the dictionary:
Example
julia> keys(D)
KeySet for a Dict{String, Int64} with 2 entries. Keys:
"B"
"A"
julia>
Values
To be continued... Each key in the dictionary has a corresponding value.
Viewing All Values in a Dictionary
We can use values()
to view all values in a dictionary:
Example
julia> D=Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia> values(D)
ValueIterator for a Dict{String, Int64} with 2 entries. Values:
2
1
julia>
Dictionary as an Iterable Object
We can treat the dictionary as an iterable object to view key/value pairs:
Example
julia> D=Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia> for kv in D
println(kv)
end
"B" => 2
"A" => 1
In the example, kv
is a tuple containing each key/value pair.
Sorting Dictionaries
Dictionaries are unordered, but we can use the sort()
function to sort them:
Example
julia> tutorialpro_dict = Dict("R" => 100, "S" => 220, "T" => 350, "U" => 400, "V" => 575, "W" => 670)
Dict{String, Int64} with 6 entries:
"S" => 220
"U" => 400
"T" => 350
"W" => 670
"V" => 575
"R" => 100
julia> for key in sort(collect(keys(tutorialpro_dict)))
println("$key => $(tutorialpro_dict[key])")
end
R => 100
S => 220
T => 350
U => 400
V => 575
W => 670
We can use the SortedDict
data type from the DataStructures.jl package to keep the dictionary sorted at all times.
To use the DataStructures package, it needs to be installed first. You can add SortedDict
in the REPL's Pkg mode using the add
command.
Enter the ]
symbol in the REPL to enter pkg mode.
Entering pkg Mode
julia> ] # Enter ] to enter pkg mode
Package addition syntax:
add package_name
After adding the DataStructures package, the following examples can run normally:
(@v1.7) pkg> add DataStructures
add https://github.com/fredrikekre/ImportMacros.jl
Local package:
add local_path/package_name.jl
Example
julia> import DataStructures
julia> tutorialpro_dict = DataStructures.SortedDict("S" => 220, "T" => 350, "U" => 400, "V" => 575, "W" => 670)
DataStructures.SortedDict{String, Int64, Base.Order.ForwardOrdering} with 5 entries:
"S" => 220
"T" => 350
"U" => 400
"V" => 575
"W" => 670
julia> tutorialpro_dict["R"] = 100
100
julia> tutorialpro_dict
DataStructures.SortedDict{String, Int64, Base.Order.ForwardOrdering} with 6 entries:
"R" => 100
"S" => 220
"T" => 350
"U" => 400
"V" => 575
"W" => 670
Set
Here are the differences between a set and other types of collections:
- Elements in a set are unique.
- The order of elements in a set is not important.
Sets are used to create lists without duplicates.
Creating a Set
Using the Set constructor, we can create sets as follows:
Example
julia> var_site = Set()
Set{Any}()
julia> num_primes = Set{Int64}()
Set{Int64}()
julia> var_site = Set{String}(["Google", "tutorialpro", "Taobao"])
Set{String} with 3 elements:
"Google"
"Taobao"
"tutorialpro"
We can use the push!()
function to add elements to the set, as shown below:
Example
julia> push!(var_site, "Wiki")
Set{String} with 4 elements:
"Google"
"Wiki"
"Taobao"
"tutorialpro"
We can use the in()
function to check if an element exists in the set:
Example
julia> in("tutorialpro", var_site)
true
julia> in("Zhihu", var_site)
false
Common Operations
Union, intersection, and difference are common operations we can perform on sets, corresponding to the functions union(), intersect(), and setdiff().
Union
Example
julia> A = Set{String}(["red", "green", "blue", "black"])
Set{String} with 4 elements:
"blue"
"green"
"black"
"red"
julia> B = Set(["red", "orange", "yellow", "green", "blue", "indigo", "violet"])
Set{String} with 7 elements:
"indigo"
"yellow"
"orange"
"blue"
"violet"
"green"
"red"
julia> union(A, B)
Set{String} with 8 elements:
"indigo"
"green"
"black"
"yellow"
"orange"
"blue"
"violet"
"red"
Intersection
The intersection of sets A and B is the set of all elements that are both in A and B.
Example
julia> intersect(A, B)
Set{String} with 3 elements:
"blue"
"green"
"red"
Difference
The difference of sets A and B is the set of all elements that are in A but not in B.
Example
julia> setdiff(A, B)
Set{String} with 1 element:
"black"
Common Functions for Dictionaries and Sets
The following examples demonstrate common functions used with dictionaries, which also apply to sets:
Create two dictionaries dict1 and dict2:
Example
julia> dict1 = Dict(100 => "X", 220 => "Y")
Dict{Int64, String} with 2 entries:
100 => "X"
220 => "Y"
julia> dict2 = Dict(220 => "Y", 300 => "Z", 450 => "W")
Dict{Int64, String} with 3 entries:
450 => "W"
220 => "Y"
300 => "Z"
Dictionary union:
Example
julia> union(dict1, dict2)
4-element Array{Pair{Int64, String}, 1}:
100 => "X"
220 => "Y"
450 => "W"
300 => "Z"
julia> intersect(dict1, dict2)
1-element Array{Pair{Int64, String}, 1}:
220 => "Y"
Dictionary difference:
Example
julia> setdiff(dict1, dict2)
1-element Array{Pair{Int64, String}, 1}:
100 => "X"
Merge dictionaries:
Example
julia> merge(dict1, dict2)
Dict{Int64, String} with 4 entries:
100 => "X"
450 => "W"
220 => "Y"
300 => "Z"
Find the minimum value in the dictionary:
Example
julia> dict1
Dict{Int64, String} with 2 entries:
100 => "X"
220 => "Y"
julia> findmin(dict1)
("X", 100)