From Julia: Dictionaries and Pairs
Code 1
julia> d = Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
julia> push!(d,("C",3))
ERROR: MethodError: no method matching push!(::Dict{String, Int64}, ::Tuple{String, Int64})
julia> push!(d,"C" => 3)
Dict{String, Int64} with 3 entries:
"B" => 2
"A" => 1
"C" => 3
julia> typeof("C" => 3)
Pair{String, Int64}
Dictionaries in Julia are data types that pair Keys and Values, much like in other programming languages. A slight difference in Julia is that dictionaries are seen as a collection of Pairs. As can be seen in the provided execution example, a pair is an element that constitutes the dictionary. Keys and Values are linked through the right arrow =>
, and they themselves take the form of a Pair
data type.
The following example shows how to replace parts of a string in Julia.
julia> replace("qwerty", "q"=>"Q")
"Qwerty"
If there’s something that sets it apart from Python, it’s that pairs can exist independently of a dictionary. Instead of viewing the dictionary as a collection containing just one pair, pairs themselves can be viewed as data, which is why Julia code may utilize pairs in a way that seems like a new syntax. Regardless of whether you use it or not, it’s something you should be able to read.
Environment
- OS: Windows
- julia: v1.6.3