I want to loop through and print the (key, value) pairs of a dictionary in Julia. How can I do this?
I see how to initalize a dictionary in Julia here, but I want to loop through it as well.
A dictionary in Julia can be created with a pre-defined keyword Dict(). This keyword accepts key-value pairs as arguments and generates a dictionary by defining its data type based on the data type of the key-value pairs. One can also pre-define the data type of the dictionary if the data type of the values is known.
To test for the presence of a key in a dictionary, use haskey or k in keys(dict) . Base. eltype — Function.
The solution is relatively simple:
x = Dict("a"=>"A", "b"=>"B", "c"=>"C")
for (key, value) in x
print(key); print(value)
end
# Output: cCbBaA
Check out the Julia docs for Base.Dict to learn more about functions you can apply to a Dictionary in Julia!
you can also use this solution:
x = Dict("a"=>"A", "b"=>"B", "c"=>"C")
for item in x
print(item.first)
print(" : ")
println(item.second)
end
# output:
# c : C
# b : B
# a : A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With