Towards AI Can Help your Team Adopt AI: Corporate Training, Consulting, and Talent Solutions.

Publication

Julia Tuple and Dictionary
Latest

Julia Tuple and Dictionary

Last Updated on October 17, 2022 by Editorial Team

Author(s): Vivek Chaudhary

Originally published on Towards AI the World’s Leading AI and Technology News and Media Company. If you are building an AI-related product or service, we invite you to consider becoming an AI sponsor. At Towards AI, we help scale AI and technology startups. Let us help you unleash your technology to the masses.

The objective of this article is to understand Julia Data Structures Tuple and Dictionary and the various operations associated with them.

TUPLES: are an immutable collection of distinct values of the same or different datatypes separated by commas.

Syntax: (item1, item2, item3…)

Dictionary: is a collection of key-value pairs, where each value in the dictionary can be accessed with its key. These key-value pairs need not be of the same data type.

Syntax: Dict(key1 => value1, key2 => value2, …)

Tuples and methods()

#create an empty tuple
t1=()
println(“If a Tuple is empty returns “, isempty(t1))
t1=(“julia”,”python”,”sql”)
println(“If a Tuple is non-empty returns “,isempty(t1))
Output:
If a Tuple is empty returns true
If a Tuple is non-empty returns false

Indexing, Slicing, Iteration and Assignment

#declare a tuple beverage
beverage= (“coffee”,”tea”,”greentea”,”grrencoffee”,”ginger tea”)
#Indexing
println(beverage[1])
Output: coffee
println(beverage[0]) #index in julia starts from 1
BoundsError: attempt to access NTuple{5, String} at index [0]

Stacktrace:
[1] getindex(t::Tuple, i::Int64)
@ Base .\tuple.jl:29
[2] top-level scope
@ In[7]:2
[3] eval
@ .\boot.jl:373 [inlined]
[4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1196
#Slicing
println(beverage[2:4])
Output:
("tea", "greentea", "grrencoffee")
#Iteration
println("iterating over tuple :")
for i in beverage
println(i)
end
Output:
iterating over tuple :
coffee
tea
greentea
grrencoffee
ginger tea
#Tuple manipulation:
beverage[3]="chamomile tea"
Output:
MethodError: no method matching setindex!(::NTuple{4, String}, ::String, ::Int64)

Stacktrace:
[1] top-level scope
@ In[7]:2
[2] eval
@ .\boot.jl:373 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1196

#Note: Tuples are immutable, and they don’t support item assignment.

Tuple methods()

#reverse a tuple
rev= reverse(beverage)
println(rev)
Output:("ginger tea", "grrencoffee", "greentea", "tea", "coffee")
#length of tuple
println(“length of tuple “,length(beverage))
Output: length of tuple 5
#check if empty or not
println(isempty(beverage))
Output: false

Named Tuples: are just like Tuples except that each element additionally has a name!
They have a special syntax using “=” inside a tuple.
Syntax:
(name1 = item1, name2 = item2, …)

lang= (l1=”julia”,l2=”python”,l3=”SQL”)
println(lang)
Output: (l1 = "julia", l2 = "python", l3 = "SQL")
println(lang[2])
Output: python
println(lang.l1)
Output: julia

Dictionary and methods()

#create a dictionary
empIDs= Dict(“vivek”=>121,”aniket”=>134,”jagdish”=>101)
println(typeof(empIDs))
println(empIDs)
Output:
Dict{String, Int64}
Dict("jagdish" => 101, "vivek" => 121, "aniket" => 134)
#create dict from tuple
eds=[("vivek",2000),("jagdish",5000),("aniket",3500)]
println(typeof(eds))
println(eds)
Output:
Vector{Tuple{String, Int64}}
[("vivek", 2000), ("jagdish", 5000), ("aniket", 3500)]
#conver the tuple into dictionary
edict=Dict(eds)
println(typeof(edict))
println(edict)
Output:
Dict{String, Int64}
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)

Access Dictionary items

println(edict)
Output:
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)
key=keys(edict)
println(“keys are :”,key)
Output: keys are :["jagdish", "vivek", "aniket"]
val=values(edict)
println(“values are :”, val)
Output: values are :[5000, 2000, 3500]
#Iterate over dictionary using for loop 
for (key,val) in edict
println(key,"=>",val)
end
Output:
jagdish=>5000
vivek=>2000
aniket=>3500

Dictionary methods()

get() and getkey()

#get() method: Return the value stored for the given key
#syntax: get(collection, key, default)
println(edict)
Output:
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)
println(get(edict,"vivek",-1))
Output: 2000
#default value is mandatory otherwise it throws error
println("Key not found ",get(edict,"viv",0))
Output: Key not found 0
#wihtout default value
println("Key not found ",get(edict,"viv"))
Output:
MethodError: no method matching get(::Dict{String, Int64}, ::String)
Closest candidates are:
get(::Dict{K, V}, ::Any, ::Any) where {K, V} at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\base\dict.jl:506
get(::IJulia.IJuliaStdio, ::Any, ::Any) at C:\Users\lenovo\.julia\packages\IJulia\e8kqU\src\stdio.jl:21
get(::Test.GenericDict, ::Any, ::Any) at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\stdlib\v1.7\Test\src\Test.jl:1800
...

Stacktrace:
[1] top-level scope
@ In[57]:7
[2] eval
@ .\boot.jl:373 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1196
#getkey()
Return the key matching argument key if one exists in collection, otherwise return default.
println(getkey(edict,"aniket",-1))
Output: aniket
println(getkey(edict,"viv",-1))
Output: -1

delete() items

println(edict)
Output:
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)
delete!(edict,”vivek”)
println(edict)
Output:
Dict("jagdish" => 5000, "aniket" => 3500)
#delete a non-existing item
delete!(edict,"viv")
Output:
Dict{String, Int64} with 2 entries:
"jagdish" => 5000
"aniket" => 3500

merge() dictionaries

#merge dictionaries using merge()
d1 = Dict(“a”=>1, “b”=>9, “c”=>3)
d2 = Dict(“e”=>7, “f”=>2, “h”=>5)
println(merge(d1,d2))
Output:
Dict("f" => 2, "c" => 3, "e" => 7, "b" => 9, "a" => 1, "h" => 5)
#common keys present
d1 = Dict("a"=>1, "b"=>9, "c"=>3)
d2 = Dict("e"=>7, "b"=>2, "h"=>5)
println(merge(d1,d2))
Output:
Dict("c" => 3, "e" => 7, "b" => 2, "a" => 1, "h" => 5)
#merge dictionaries using mergewith()
d1 = Dict("a"=>1, "b"=>9, "c"=>3)
d2 = Dict("e"=>7, "b"=>2, "h"=>5)
println(mergewith!(+,d1,d2))
Output:
Dict("c" => 3, "e" => 7, "b" => 11, "a" => 1, "h" => 5)

add and change dict items

#add new item to a dict
println(edict)
Output: Dict("jagdish" => 5000, "aniket" => 3500)
edict[“vivek”]=2700
println(edict)
Output: Dict("jagdish" => 5000, "vivek" => 2700, "aniket" => 3500)
#change dict vaue for a key
println(edict)
Output: Dict("jagdish" => 5000, "vivek" => 2700, "aniket" => 3500)
edict["vivek"]=4000
println(edict)
Output: Dict("jagdish" => 5000, "vivek" => 4000, "aniket" => 3500)

To Summarize:

  • Julia tuple and tuple methods.
  • Dictionary and methods.

Thanks for reading my blog and supporting the content. Appreciation always helps to keep up the spirit. I will try my best to keep coming up with quality content. Connect with me to get updates about upcoming new content.

Keep Supporting.


Julia Tuple and Dictionary was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

Join thousands of data leaders on the AI newsletter. It’s free, we don’t spam, and we never share your email address. Keep up to date with the latest work in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI

Feedback ↓