What are dictionaries and sets in Julia?
Overview
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:
- Dictionaries are organized in key-value pairs. Sets are not.
- Keyword for a Dictionary is
Dict()while set isSet(). - Dictionaries and sets are both mutable. This means we can always alter, change, or delete the values specified.
- They are both unordered. This means that values do not maintain the order in which they are specified. So, an item can appear last even if it was specified first.
Dictionaries
Syntax
Dictionary_name[key_name => value_name]
or
Dictionary_name[:key_name => value_name]
How to create a dictionary
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)
Accessing elements in a dictionary
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])
Using get() method
The syntax is as below:
get(Dictionary_name, Key_name, Default Value)
Example
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)
Sets
Syntax
Below is the syntax for creating a set:
Setname = Set([Value1, Value2,....])
Creating and accessing elements of a set
#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.