How to create a Julia dictionary from arrays of keys and values
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.
Syntax
Let's view the syntax below.
Dict(zip(array of keys, array of values))
Parameters
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.
Code example
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)))
Code explanation
Line 2: We declare the variable
studentsand initialize it with students’ names as an array of strings. We will use the array ofstudentsas keys to the dictionary.Line 5: We declare a variable
agesand initialize it with students' ages as an array of integers. We will use the arrayagesas values in the dictionary.Line 8: We create a dictionary and display it. We will use the
zip()function to zip the two arrays ofstudentsandages, and pass the zip object to theDict()function, which creates a dictionary.
Free Resources