Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display dictionary key/value in loop?

I'm assigning each dictionary element into one variable. Is there a way to then get the related key/value out of the variable?

This doesn't work:

for letter = Dict("a"=>"A", "b"=>"B", "c"=>"C")
println("$letter[1] upper case is $letter[2]")
end

Output:
"c"=>"C"[1] upper case is "c"=>"C"[2]
"b"=>"B"[1] upper case is "b"=>"B"[2]
"a"=>"A"[1] upper case is "a"=>"A"[2]

I'd like the output to look like this:
"c upper case is C"
"b upper case is B"
"a upper case is A"

I know it can be done using a tuple for the iterated variable but I'd like to use a single variable.

like image 796
4thSpace Avatar asked Mar 31 '26 20:03

4thSpace


1 Answers

If you really don't want to loop by (key, value) then all you are missing are the brackets after the $ in println:

for letter in Dict("a"=>"A", "b"=>"B", "c"=>"C")
    println("$(letter[1]) upper case is $(letter[2])")
end

Out:

c upper case is C
b upper case is B
a upper case is A

I would still recommend looping for (key, value) in my_dict as that's more readable.

like image 142
niczky12 Avatar answered Apr 03 '26 17:04

niczky12



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!