Introduction to Dictionary in Julia programming [Julia Tutorial: 05 ]

Hafez Ahmad
2 min readJul 10, 2020

Dictionary in Julia is a collection of key-value pairs where each value in the dictionary can be accessed with its key.

#let’s create an empty dictionary
d1=Dict()
print(d1)
output: Dict{Any,Any} with 0 entries
#The kind of dictionary is surrounded by curly braces: the keys are of type Any and also the values are of type Any

Now, we can create a new dictionary with keys and values

d2=Dict(“a”=>1,”b”=>2,”c”=>3)output: Dict{String,Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1

Elements from the dictionary can be accessed by using the keys.

print(keys(d2))output:["c", "b", "a"]println(values(d2))
output: [3, 2, 1]

now we can access

d2[“a”]
output: 1

iterate object through loop . all the key value paris of a dictionary can be printed at once with the use for loop.

for i in d2
println(i)
end
output:
"c" => 3
"b" => 2
"a" => 1

you can access each key one by one


for i in keys(d2)
println(i,” => “, d2[i])
end
c => 3
b => 2
a => 1

there is an alternative method

for (key, value) in d2
println(key, “ => “,value)
end

you can add a new key


d2[“d”]=4
println(d2)output: Dict("c" => 3,"b" => 2,"a" => 1,"d" => 4)

we can delete key

delete!(d2,”d”)output: Dict("c" => 3,"b" => 2,"a" => 1)

we write a single map function in the dictionary

println(map(uppercase,collect(keys(d2))))
output: ["C", "B", "A"]

we can union, it is almost as merge

d3=Dict(“f”=>5,”g”=>7)
println(union(d2,d3))
output: ["c" => 3, "b" => 2, "a" => 1, "f" => 5, "g" => 7]
println(intersect(d2,d3))
output: Pair{String,Int64}[]

filter where key = a

filter((k,v) ->k==”a”,d2)
output: "a" => 1

you can check “a” in the d2 dictionary, this will give true , if it does otherwise it will give false

haskey(d2,”a”)
output: true

we are now creating a vector to dictionary conversion function

function vector_to_diction(v,le)
d=Dict()
@assert(length(v)==length(le))
for i =1:length(v)
d[le[i]]=v[i]
end
d
end
v=[2,5,6,7]
le=[“a”,”b”,”c”,”d”]
vector_to_diction(v,le)
output: Dict{Any,Any} with 4 entries:
"c" => 6
"b" => 5
"a" => 2
"d" => 7

now, dictionary to a vector function

function d_to_v(d)
v=[]
for i in keys(d)
push!(v,d[i])
end
v
end
d_to_v(d1)output: 4-element Array{Any,1}:
6
5
2
7

--

--

Hafez Ahmad

I am an Oceanographer. I am using Python, R, MATLAB, Julia, and ArcGIS for data analysis, data visualization, Machine learning, and Ocean/ climate modeling.