- Julia 1.0 Programming Complete Reference Guide
- Ivo Balbaert Adrian Salceanu
- 369字
- 2021-06-24 14:21:48
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))
- 現(xiàn)代C++編程:從入門到實(shí)踐
- Mastering Visual Studio 2017
- Java入門經(jīng)典(第6版)
- vSphere High Performance Cookbook
- Vue.js快速入門與深入實(shí)戰(zhàn)
- Monitoring Elasticsearch
- SQL基礎(chǔ)教程(視頻教學(xué)版)
- Unreal Engine 4 Shaders and Effects Cookbook
- 持續(xù)輕量級(jí)Java EE開發(fā):編寫可測(cè)試的代碼
- 圖數(shù)據(jù)庫實(shí)戰(zhàn)
- LabVIEW虛擬儀器入門與測(cè)控應(yīng)用100例
- Quantum Computing and Blockchain in Business
- Python入門很輕松(微課超值版)
- 玩轉(zhuǎn).NET Micro Framework移植:基于STM32F10x處理器
- Groovy 2 Cookbook