Tuesday, August 15, 2017

Julia - Language - Collection - Dictionary

Dictionaries are part of standard Julia Language collections. Information are stored in it in form of key-value pairs. We can think of them as arrays in which indices are keys with corresponding value. 

Standard Julia Array:


array value 45 65 20 8
array index 1 2 3 4




Standard Julia Dictionary:



dictionary value Panjim Hyderabad Bengaluru Chandigarh
dictionary key Goa Telangana Karnataka Punjab



This dictionary can be created using the following syntax:

Technique 1: Using => shorthand

julia> dict_country_capitals1 = Dict("Goa" => "Panjim", "Telangana" => "Hyderabad", "Karnataka" => "Bengaluru", "Punjab" => "Chandigarh")
Dict{String,String} with 4 entries:
  "Punjab"    => "Chandigarh"
  "Telangana" => "Hyderabad"
  "Karnataka" => "Bengaluru"
  "Goa"       => "Panjim"


julia>

The symbol => is a shorthand for the Pair function. 

Technique 2: Using Pair function

The second technique is to use the Pair Function to create this key-value pair:

julia> dict_country_capitals2 = Dict(Pair("Goa" , "Panjim") , Pair("Telangana" , "Hyderabad") , Pair("Karnataka" , "Bengaluru") , Pair("Punjab" , "Chandigarh"))
Dict{String,String} with 4 entries:
  "Punjab"    => "Chandigarh"
  "Telangana" => "Hyderabad"
  "Karnataka" => "Bengaluru"
  "Goa"       => "Panjim"


julia> 

To access the value in a Dictionary, we must pass the key as a input parameter to the Dictionary:

julia> dict_country_capitals1["Goa"]
"Panjim"

julia> 

Technique 3: Dynamic Dictionary - Key-Value are any datatype
We can also create Dynamic Dictionary in which any datatype can be a Key and Value.

julia> dict3 = Dict{Any,Any}(1 => "I dont know!!","Goa" => "Panjim", "Telangana" => "Hyderabad", "Karnataka" => "Bengaluru", "Punjab" => "Chandigarh")
Dict{Any,Any} with 5 entries:
  "Punjab"    => "Chandigarh"
  "Telangana" => "Hyderabad"
  "Karnataka" => "Bengaluru"
  "Goa"       => "Panjim"
  1           => "I dont know!!"

julia> dict3
Dict{Any,Any} with 5 entries:
  "Punjab"    => "Chandigarh"
  "Telangana" => "Hyderabad"
  "Karnataka" => "Bengaluru"
  "Goa"       => "Panjim"
  1           => "I dont know!!"

Accessing the Dictionary Values using Keys:

julia> dict3[1]
"I dont know!!"

julia> dict3["Goa"]
"Panjim"

julia> 


Technique 4: Symbol Notation

julia> dict_symbol_notation = Dict(:A => "America", :B => "Asia", :C => "Australia")
Dict{Symbol,String} with 3 entries:
  :A => "America"
  :B => "Asia"
  :C => "Australia"

Accessing the Dictionary Values using Keys:

julia> dict_symbol_notation[:B]
"Asia"

julia> 


Handling Exceptions: In case a key does not exist in a dictionary, and we try to access it - then Julia will throw an error. To avoid an error, we can use the get() function at the time of accessing:

Julia throws error, if the key is not found. 

julia> dict_symbol_notation[:H]
ERROR: KeyError: key :H not found
Stacktrace:
 [1] getindex(::Dict{Symbol,String}, ::Symbol) at ./dict.jl:474

using get() function avoids Julia Error:

julia> get(dict_symbol_notation,:H,"Key not found!!")
"Key not found!!"

julia> 

in() function: to check if a key value pair exists in a dictionary:

julia> in((:A => "America"),dict_symbol_notation)
true

haskey() function: to check if a key exists in a dictionary:

julia> haskey(dict_symbol_notation,:A)
true

julia> haskey(dict_symbol_notation,:H)
false

Since, H is not existing, to add a key-value pair to a dictionary is very easy. We will use the assignment operator.

julia> dict_symbol_notation[:H] = "Africa"
"Africa"

julia> dict_symbol_notation
Dict{Symbol,String} with 4 entries:
  :A => "America"
  :H => "Africa"
  :B => "Asia"
  :C => "Australia"

julia> 

Therefore, dictionaries are mutable. That means, that their values can be changed. Let us edit the value for the symbol, :C

julia> dict_symbol_notation[:C] = "Europe"
"Europe"

julia> dict_symbol_notation
Dict{Symbol,String} with 4 entries:
  :A => "America"
  :H => "Africa"
  :B => "Asia"
  :C => "Europe"

julia> 

delete!() function: to delete a entry from dictionary:

julia> delete!(dict_symbol_notation,:C)
Dict{Symbol,String} with 3 entries:
  :A => "America"
  :H => "Africa"
  :B => "Asia"

julia> 

length() function: to know the number of key/values in a dictionary:

julia> length(dict_symbol_notation)
3

A dictionary has no size() and no ndims()

julia> size(dict_symbol_notation)
ERROR: MethodError: no method matching size(::Dict{Symbol,String})
Closest candidates are:
  size(::Any, ::Integer, ::Integer, ::Integer...) where N at abstractarray.jl:30
  size(::Char) at char.jl:13
  size(::Char, ::Any) at char.jl:14
  ...

julia> 

A for loop can be used to read and populate a dictionary:

julia> for (k,v) in dict_symbol_notation
       println("The key $(k) has a value $(v)")
       end
The key A has a value America
The key H has a value Africa
The key B has a value Asia

julia> 


To convert a standard Julia Array to Dictionary, Let us consider a standard Julia array of Strings:

julia> procedure_values = ["Cardiology","Physiology","Microbiology"]
3-element Array{String,1}:
 "Cardiology"  
 "Physiology"  
 "Microbiology"

Now, let us create a dictionary from this:

julia> procedure_dict = Dict{AbstractString,AbstractString}()
Dict{AbstractString,AbstractString} with 0 entries

julia> procedure_dict
Dict{AbstractString,AbstractString} with 0 entries

julia> enumerate(procedure_values)
Enumerate{Array{String,1}}(String["Cardiology", "Physiology", "Microbiology"])

Use for loop and enumerate function to fill the dictionary:

julia> for (s,n) in enumerate(procedure_values)
       procedure_dict["x_$(s)"] = n
       end

Check the Keys in the new dictionary using the keys() function:

julia> keys(procedure_dict)
Base.KeyIterator for a Dict{AbstractString,AbstractString} with 3 entries. Keys:
  "x_1"
  "x_2"
  "x_3"


Sorting a dictionary output:

Let us create a dictionary. 

julia> dict4Sort = Dict{AbstractString,Int16}("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5, "f" => 6)
Dict{AbstractString,Int16} with 6 entries:
  "f" => 6
  "c" => 3
  "e" => 5
  "b" => 2
  "a" => 1
  "d" => 4

julia>

We can see that the output is not in sorted format. To sort them, we need to use the sort function available in Julia.

First, let us list the keys in the dictionary using the keys() function:

julia> keys(dict4Sort)
Base.KeyIterator for a Dict{AbstractString,Int16} with 6 entries. Keys:
  "f"
  "c"
  "e"
  "b"
  "a"
  "d"

Let us now use the collect function to gather the keys into an array:

julia> collect(keys(dict4Sort))
6-element Array{AbstractString,1}:
 "f"
 "c"
 "e"
 "b"
 "a"
 "d"

We can use the sort() function to provide a sorted output:

julia> sort(collect(keys(dict4Sort)))
6-element Array{AbstractString,1}:
 "a"
 "b"
 "c"
 "d"
 "e"
 "f"

julia> 

Using a for loop we can print the values:

julia> for i in sort(collect(keys(dict4Sort)))
       println("$(i) => $(dict4Sort[i])")
       end
a => 1
b => 2
c => 3
d => 4
e => 5
f => 6


julia> 


No comments:

Post a Comment