A dictionary is used to store data in key-value pairs. The keys in a dictionary should be unique. The values are queried based on keys in a dictionary.
We can create a Julia dictionary from arrays of keys and values using the zip()
function.
Let's view the syntax below.
Dict(zip(array of keys, array of values))
zip()
: This function takes arrays as parameters and returns a zip object.
Dict()
: We pass the zip object through this function to convert it to a dictionary.
Let's take a look at an example of this below.
#given array of keysstudents = ["John", "Hady", "Charlie", "Celine"]#given array of valuesages = [18, 17, 19, 20]#create dict from arrays of keys and valuesprintln(Dict(zip(students, ages)))
Line 2: We declare the variable students
and initialize it with students’ names as an array of strings. We will use the array of students
as keys to the dictionary.
Line 5: We declare a variable ages
and initialize it with students' ages as an array of integers. We will use the array ages
as values in the dictionary.
Line 8: We create a dictionary and display it. We will use the zip()
function to zip the two arrays of students
and ages
, and pass the zip object to the Dict()
function, which creates a dictionary.
Free Resources