Julia 101
--
Lesson 5: Dictionaries
In Julia, a dictionary is a collection of key-value pairs, where each key is associated with a value. Dictionaries are an essential data structure for many programming tasks, such as storing and retrieving data, building indices, and caching results. In this post, we will explore what dictionaries are and how to work with them in Julia.
Creating a Dictionary
Creating a dictionary in Julia is straightforward. We can create an empty dictionary using the Dict()
function, like this:
my_dict = Dict()
Or we can create a dictionary with initial values using the same Dict()
function, like this:
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
In this code, the keys are the strings “apple”, “banana”, and “cherry”, and the values are the integers 3, 6, and 9, respectively.
Adding and Removing Elements from a Dictionary
To add a new key-value pair to a dictionary, we can use the syntax my_dict[key] = value
.
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
my_dict["orange"] = 12
A new key-value pair is added to the my_dict
dictionary with the key "orange" and the value 12.
To remove a key-value pair from a dictionary, we can use the pop!()
function.
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
pop!(my_dict, "banana")
The key-value pair with the key “banana” is removed from the my_dict
dictionary.
Accessing Elements in a Dictionary
We can access the value associated with a key in a dictionary using indexing.
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
my_dict["banana"] # Returns 6
The value associated with the key “banana” is accessed using indexing.
Iterating over a Dictionary
We can iterate over a dictionary using a for loop.
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
for (key, value) in my_dict
println("$key: $value")
end
This code will print each key-value pair in the dictionary on a separate line.
Reverse Lookup (Checking if a Key is in a Dictionary)
To check if a key is in a dictionary, we can use the haskey()
function.
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
haskey(my_dict, "banana") # Returns true
haskey(my_dict, "orange") # Returns false
In this code, the haskey()
function is used to check if the keys "banana" and "orange" are in the my_dict
dictionary.
Updating a Dictionary
To update the value associated with a key in a dictionary, we can use the syntax my_dict[key] = new_value
.
my_dict = Dict("apple" => 3, "banana" => 6, "cherry" => 9)
my_dict["banana"] = 10