如何在循环中显示字典键/值?(How to display dictionary key/value in loop?)

我将每个字典元素分配到一个变量中。 有没有办法从变量中获取相关的键/值?

这不起作用:

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

输出: “c”=>“C”[1]大写是“c”=>“C”[2] “b”=>“B”[1]大写是“b”=>“B”[2] “a”=>“A”[1]大写是“a”=>“A”[2]

我希望输出看起来像这样: “c大写字母是C” “b大写是B” “大写是A”

我知道可以使用迭代变量的元组来完成,但我想使用单个变量。

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.

最满意答案

如果你真的不想循环(key, value)那么你所缺少的是$ in println之后的括号:

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

日期:

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

我仍然建议(key, value) in my_dict为(key, value) in my_dict循环,因为它更具可读性。

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.

更多推荐