- 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))
- LabVIEW Graphical Programming Cookbook
- 軟件架構設計:大型網站技術架構與業務架構融合之道
- Learning Docker
- Android Studio Essentials
- Rake Task Management Essentials
- Python進階編程:編寫更高效、優雅的Python代碼
- Learning Informatica PowerCenter 10.x(Second Edition)
- Python數據分析(第2版)
- Podman實戰
- ArcGIS By Example
- 零基礎學單片機C語言程序設計
- 執劍而舞:用代碼創作藝術
- PHP+Ajax+jQuery網站開發項目式教程
- Node Cookbook(Second Edition)
- Access 2010中文版項目教程