DEV Community

Cover image for Learning Julia (8): About Dict Type
Z. QIU
Z. QIU

Posted on

Learning Julia (8): About Dict Type

Dict is the standard dictionary. Its implementation uses hash as the hashing function for the key, and isequal to determine equality. Define these two functions for custom types to override how they are stored in a hash table.

I plot in my neo4j db the sub-graph about Dict type to get a better understand of its type hierarchy:
Alt Text

Dict is quite similar to dictionary in Python. So I just show some of my test code below.

d1 = Dict("a"=> 11, "b" => 22, "c" => 33)
println("d1: $d1, type: ", typeof(d1))

ks = keys(d1)  # get all keys of dict

println("ks: $ks, type: ", typeof(ks))

arr_ks = collect(keys(d1))  # put all keys into a list

arr2_ks = [k for (k,v) in d1]   # array comprehension from a dict
println("arr_ks: $arr_ks, arr2_ks: $arr2_ks")

vs = values(d1)
println("vs: $vs, type: ", typeof(vs))


arr_vs = [v for (k,v) in d1]   # array comprehension from a dict

println("arr_vs: $arr_vs")

d1["d"] = 44    # add new item to a dict

for (key, val) in d1
    println("  key: $key, value: $val")
end

println(haskey(d1, "a"))    # to check if dict has a certain key
pop!(d1, "d")               # remove an item

println("d1: $d1, type: ", typeof(d1))
println(haskey(d1, "d"))
Enter fullscreen mode Exit fullscreen mode

Execution output:

Alt Text

d2 = Dict(:a=> 11, :b => 22, :c => 33)           #  symbol-keys
println("d2: $d2")
println(keys(d2))

for (key, val) in d2
    println("  key: $key, value: $val")
end
println(d2[:a])

try 
    d2["d"] = 44         # try to add a string-key to a dict with symbol-keys
    println("d2: $d2")
catch e
    print(e)
end

Enter fullscreen mode Exit fullscreen mode

Execution output:
Alt Text

Top comments (0)