Dictionaries and sets are data structures in Julia. Data structures help us store data into computer memory in an organized way.
Dictionaries and sets have the below characteristics:
Dict()
while set is Set()
.Dictionary_name[key_name => value_name]
or
Dictionary_name[:key_name => value_name]
The code below shows how to create a dictionary:
# Creating a dictionary# The keys can either be strings or integersdata = Dict("a" => 1, "b" => 2, 1 => "Hello")println(data)data_2 = Dict(1 => 1, "ben" => 10)println(data_2)data_3 = Dict(:a => 1, :b => "one")println(data_3)
We can access elements in a dictionary using keys or using the get()
method as shown:
data = Dict("a" => 1, "b" => 2, 1 => "Hello")#println(data)println(data["a"])println(data[1])data_2 = Dict(1 => 1, "ben" => 10)#print(data_2)println(data_2["ben"])data_3 = Dict(:a => 1, :b => "one")println(data_3[:b])
get()
methodThe syntax is as below:
get(Dictionary_name, Key_name, Default Value)
data_3 = Dict("a" => 1, "b" => 2, 1 => "Hello")println(get(data_3, "a", 0))println(get(data_3,1,0))
Keys and values can be accessed in a similar way to the codes above.
The general syntax is:
Keys = keys(Dictionary_name)
Values = values(Dictionary_name)
Below is the syntax for creating a set:
Setname = Set([Value1, Value2,....])
#creating a set with integers onlySet1 = Set([1,2,3])println(Set1)# Creating a set with different datatypesSet3 = Set([1, 2, 3, "Tom", "Chair"])println(Set3)#Accessing the elements#Using a for loopfor i in Set1println(i)end
Note: Similar to the
get()
method in dictionaries, Julia has many methods used in dictionaries and sets. These methods help to add, delete, and manipulate the data further.