YouTip LogoYouTip

Julia Dictionaries Sets

In the previous chapters, we learned about Julia Arrays and Julia Tuples.

Arrays are a type of collection. In addition, Julia has 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 in a dictionary is separated by =>, with each key-value pair separated by a comma ,. The entire dictionary is enclosed in curly braces {}. The format is as follows:

Creating Dictionaries

The syntax for creating a dictionary is as follows:

Dict("key1" => value1, "key2" => value2,,โ€ฆ, "keyn" => valuen)

The following example creates a simple dictionary where key A corresponds to value 1, and key B corresponds to 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>

Use for to create a dictionary:

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 won't create a new one but modify the existing key.

Looking up keys

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 key/value pairs

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 = 3

3

julia> D

Dict{String, Int64} with 3 entries:

"B" =>2

"A" =>1

"C" =>3

Deleting key/value pairs

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 a dictionary

We can use the keys() function to get all keys in a dictionary:

Example

julia>keys(D)

 KeySet for a Dict{String, Int64} with 2 entries. Keys:

"B"

"A"

julia>

Values

Each key in a 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>

Dictionaries as Iterable Objects

We can use dictionaries as iterable objects 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.

Dictionary Sorting

Dictionaries are unordered, but we can use the sort() function to sort a dictionary:

Example

julia> tutorial_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(tutorial_dict)))

println("$key => $(tutorial_dict)")

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 a dictionary always sorted.

To use the DataStructures package, we need to install it first. In the REPL's Pkg mode, use the add command to add SortedDict.

Enter the symbol ] in the REPL to enter pkg mode.

Entering pkg mode

julia>]# Enter ] to enter pkg mode

The syntax for adding packages is:

add package_name

After adding the DataStructures package, the following examples can run normally:

(@v1.7) pkg> add DataStructures

For unregistered packages, you can directly specify the URL:

add https://github.com/fredrikekre/ImportMacros.jl

Local packages:

add local_path/package_name.jl

Example

julia>import DataStructures

julia> tutorial_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> tutorial_dict = 100

100

julia> tutorial_dict

 DataStructures.SortedDict{String, Int64, Base.Order.ForwardOrdering} with 6 entries:

"R" =>100

"S" =>220

"T" =>350

"U" =>400

"V" =>575

"W" =>670

Sets

Julia Sets are datasets of objects without duplicates; all elements are unique.

Here are the differences between sets and other types of collections:

  • Elements in a set are unique
  • The order of elements in a set doesn't matter

Sets are used to create lists without duplicates.

Creating Sets

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","","Taobao"])

Set{String} with 3 elements:

"Google"

"Taobao"

""

Alternatively we can also use push!() function, as arrays, to add elements in sets as follows โˆ’

We can use the push!() function to add elements to sets, as follows:

Example

julia>push!(var_site, "Wiki")

Set{String} with 4 elements:

"Google"

"Wiki"

"Taobao"

""

We can use the in() function to check if an element exists in a set:

Example

julia>in("", var_site)

true

julia>in("Zhihu", var_site)

false

Common Operations

Union, intersection, and difference are common operations we can perform on sets. The corresponding functions are union(), intersect() and setdiff().

Image 1

Union

Given two sets A and B, the set formed by combining all their elements is called the union of sets A and B.

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 containing all elements that belong to both A and B, and no other elements.

Example

julia>intersect(A, B)

Set{String} with 3 elements:

"blue"

"green"

"red"

Difference

The difference of sets A and B is the set containing all elements that belong to A but not to B, i.e., removing elements that overlap between B and A.

Example

julia>setdiff(A, B)

Set{String} with 1 element:

"black"

Common Functions for Dictionaries and Sets

In the following examples, we demonstrate common functions used in 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"

Intersect

 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"

Merging dictionaries:

Example

julia>merge(dict1, dict2)

Dict{Int64,String} with 4 entries:

100 =>"X"

450 =>"W"

220 =>"Y"

300 =>"Z"

Finding the minimum value in a dictionary:

Example

julia> dict1

Dict{Int64,String} with 2 entries:

100 =>"X"

220 =>"Y"

julia> findmin(dict1)

("X", 100)
โ† Css3 Pr Pointer EventsJulia Functions โ†’