Introduction to the Julia programming language
5 Dictionaries¶
Dictionaries¶
In [11]:
eng2sp = Dict()
eng2sp["one"] = "uno";
eng2sp["two"] = "dos";
eng2sp["one"]
"uno"
In [20]:
eng2sp = Dict("one" => "uno", "two" => "dos", "three" => "tres")
vs = values(eng2sp);
"uno" ∈ vs
true
Dictionaries have a function called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value. For example:
In [16]:
get(eng2sp, "one", "unkown")
"uno"
In [9]:
get(eng2sp, "four", "unkown")
"unkown"
Looping and Dictionaries¶
In [21]:
for en in keys(eng2sp)
println(en, " ", eng2sp[en])
end
two dos one uno three tres
The keys are in no particular order. To traverse the keys in sorted order, you can combine sort and collect
In [23]:
for en in sort(collect(keys(eng2sp)))
println(en, " ", eng2sp[en])
end
one uno three tres two dos