如何在 Julia 中循环字典?

log*_*ick 19 dictionary loops julia

我想遍历并打印 Julia 中字典的 (key, value) 对。我怎样才能做到这一点?

在这里看到了如何在 Julia 中初始化字典,但我也想遍历它。

log*_*ick 22

解决方法比较简单:

x = Dict("a"=>"A", "b"=>"B", "c"=>"C")

for (key, value) in x
    print(key); print(value)
end

# Output: cCbBaA
Run Code Online (Sandbox Code Playgroud)

查看Base.Dict 的 Julia 文档,了解有关可应用于 Julia 字典的函数的更多信息!


Moh*_*ari 8

您还可以使用此解决方案:

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
Run Code Online (Sandbox Code Playgroud)