
Keys and values – looping
To isolate the keys of a dictionary, use the keys function ki = keys(d3), with ki being a KeyIterator object, which we can use in a for loop as follows:
for k in keys(d3) println(k) end
Assuming d3 is again d3 = Dict(:A => 100, :B => 200), this prints out A and B. This also gives us an alternative way to test if a key exists with in. For example, :A in keys(d3) returns true and :Z in keys(d3) returns false.
If you want to work with an array of keys, use collect(keys(d3)), which returns a two-element Array{Symbol,1} that contains :A and :B. To obtain the values, use the values function: vi = values(d3), with vi being a ValueIterator object, which we can also loop through with for:
for v in values(d3) println(v) end
This returns 100 and 200, but the order in which the values or keys are returned is undefined.
Creating a dictionary from arrays with keys and values is trivial because we have a Dict constructor that can use these; as in the following example:
keys1 = ["J.S. Bach", "Woody Allen", "Barack Obama"] and values1 = [ 1685, 1935, 1961]
Then, d5 = Dict(zip(keys1, values1)) results in a Dict{String,Int64} with three entries as follows:
"J.S. Bach" => 1685 "Woody Allen" => 1935 "Barack Obama" => 1961
Working with both the key and value pairs in a loop is also easy. For instance, the for loop over d5 is as follows:
for (k, v) in d5 println("$k was born in $v") end
This will print the following output:
J.S. Bach was born in 1685 Barack Obama was born in 1961 Woody Allen was born in 1935
Alternatively, we can use an index in the tuple:
for p in d5 println("$(p[1]) was born in $(p[2])") end
Here are some more neat tricks, where dict is a dictionary:
- Copying the keys of a dictionary to an array with a list comprehension:
arrkey = [key for (key, value) in dict]
This is the same as collect(keys(dict)).
- Copying the values of a dictionary to an array with a list comprehension:
arrval = [value for (key, value) in dict]
This is the same as collect(values(dict))