- 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))
- HTML5移動Web開發技術
- Java異步編程實戰
- Java入門很輕松(微課超值版)
- 算法大爆炸:面試通關步步為營
- Android 9 Development Cookbook(Third Edition)
- Python王者歸來
- Scratch 3.0少兒編程與邏輯思維訓練
- Java EE核心技術與應用
- 玩轉.NET Micro Framework移植:基于STM32F10x處理器
- Instant Apache Camel Messaging System
- Robot Framework Test Automation
- Drupal 8 Development Cookbook(Second Edition)
- Flink核心技術:源碼剖析與特性開發
- ArcPy and ArcGIS(Second Edition)
- Wearable:Tech Projects with the Raspberry Pi Zero