Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a dictionary in Julia?

Tags:

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.

like image 807
logankilpatrick Avatar asked Sep 16 '19 19:09

logankilpatrick


People also ask

How to use Dictionaries in Julia?

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.

How do you check if a key is in a dictionary Julia?

To test for the presence of a key in a dictionary, use haskey or k in keys(dict) . Base. eltype — Function.


2 Answers

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!

like image 72
logankilpatrick Avatar answered Oct 07 '22 08:10

logankilpatrick


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
like image 27
Mohammad Nazari Avatar answered Oct 07 '22 10:10

Mohammad Nazari