2.4. Dictionaries#
The last collection type we will cover is the dictionary. While an array is an ordered list of values indexed by integers, a dictionary stores an unordered collection of key-value pairs.
Think of it like a real-world dictionary: you look up a word (the key) to find its definition (the value). This allows you to store and retrieve data using meaningful keys instead of integer positions, which is incredibly useful for organizing complex data.
2.4.1. Creating a Dictionary#
You can create a dictionary using the Dict()
constructor. Inside, you provide a comma-separated list of key => value
pairs.
If you know your dictionary will need to hold values of different types (like integers and floats), you can specify a more general value type at creation. Here, we’ll specify that the values will all be of type Number
, which allows for both Int64
and Float64
.
# Let's map chemical elements (keys) to their atomic numbers (values).
# We specify the types `String` for keys and `Number` for values.
atomic_info = Dict{String, Number}("Hydrogen" => 1, "Helium" => 2, "Lithium" => 3)
Dict{String, Number} with 3 entries:
"Hydrogen" => 1
"Helium" => 2
"Lithium" => 3
The output Dict{String, Number}
tells us that this dictionary maps String
keys to values of any numeric type.
2.4.2. Accessing, Adding, and Modifying Entries#
Working with dictionary entries is similar to indexing an array, but you use the key instead of an integer index.
# Access the value associated with the key "Helium".
atomic_info["Helium"]
2
Because we created the dictionary to hold any Number
, we can now change the value for Hydrogen from an integer (its atomic number) to a float (its atomic mass) without causing an error.
# Add a new element to the dictionary.
atomic_info["Beryllium"] = 4
# Modify Hydrogen's value from an Int to a Float64. This is allowed!
atomic_info["Hydrogen"] = 1.008
atomic_info
Dict{String, Number} with 4 entries:
"Hydrogen" => 1.008
"Beryllium" => 4
"Helium" => 2
"Lithium" => 3
2.4.3. Removing Entries#
To remove a key-value pair from a dictionary, you can use the mutating function delete!
.
# Remove the entry for "Lithium".
delete!(atomic_info, "Lithium")
atomic_info
Dict{String, Number} with 3 entries:
"Hydrogen" => 1.008
"Beryllium" => 4
"Helium" => 2
2.4.4. Useful Dictionary Functions#
Several functions are essential for working with dictionaries.
# `haskey()` checks if a key exists in the dictionary.
println("Does the dictionary have Helium? ", haskey(atomic_info, "Helium"))
println("Does the dictionary have Carbon? ", haskey(atomic_info, "Carbon"))
Does the dictionary have Helium? true
Does the dictionary have Carbon? false
# `keys()` returns an iterator over all the keys.
println("\nAll keys:")
for k in keys(atomic_info)
println(k)
end
All keys:
Hydrogen
Beryllium
Helium
# `values()` returns an iterator over all the values.
println("\nAll values:")
for v in values(atomic_info)
println(v)
end
All values:
1.008
4
2
You can also iterate directly over the dictionary itself, which gives you access to the key => value
pairs.
println("\nAll key-value pairs:")
for (key, value) in atomic_info
println(key, " has value ", value)
end
All key-value pairs:
Hydrogen has value 1.008
Beryllium has value 4
Helium has value 2