1, "B_1" => 2, "X" => "A_1" => 1) Di-6ren">
gpt4 book ai didi

dictionary - 将键值对添加到 Julia 语言字典中的现有键

转载 作者:行者123 更新时间:2023-12-04 14:47:08 24 4
gpt4 key购买 nike

我正在使用 Julia 1.63,目前正在尝试循环创建字典。我可以从下面的字典开始。

dict = Dict("A_1" => 1, "B_1" => 2, "X" => "A_1" => 1)
Dict{String, Any} with 3 entries:
"X" => "A_1"=>1
"B_1" => 2
"A_1" => 1

现在我想向“X”键添加键值对“B_2”=> 2

我尝试了以下方法:

push!(dict["X"],Dict("B_2" => 2))
ERROR: MethodError: no method matching push!(::Pair{String, Int64}, ::Dict{String, Int64})
Closest candidates are:
push!(::Any, ::Any, ::Any) at abstractarray.jl:2387
push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2388
push!(::AbstractChannel, ::Any) at channels.jl:10

push!(dict["X"],"B_2" => 2)
ERROR: MethodError: no method matching push!(::Pair{String, Int64}, ::Pair{String, Int64})
Closest candidates are:
push!(::Any, ::Any, ::Any) at abstractarray.jl:2387
push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2388
push!(::AbstractChannel, ::Any) at channels.jl:10

令我困惑的一件事是它在字典的上层起作用。

push!(dict,"B_2" => 2)
Dict{String, Any} with 4 entries:
"B_2" => 2
"X" => "A_1"=>1
"B_1" => 2
"A_1" => 1

有什么明显的我遗漏的吗?感谢您的帮助。

最佳答案

问题是 "X" 的值不是 Dict,而是 Pair。如果您想将多个 Pair 分配给一个键,您应该改用 Dict。您必须相应地对其进行初始化。

julia> dict = Dict("A_1" => 1, "B_1" => 2, "X" => Dict("A_1" => 1))
Dict{String, Any} with 3 entries:
"X" => Dict("A_1"=>1)
"B_1" => 2
"A_1" => 1
julia> push!(dict["X"],"B_2" => 2)
Dict{String, Int64} with 2 entries:
"B_2" => 2
"A_1" => 1
julia> dict
Dict{String, Any} with 3 entries:
"X" => Dict("B_2"=>2, "A_1"=>1)
"B_1" => 2
"A_1" => 1

关于dictionary - 将键值对添加到 Julia 语言字典中的现有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69827851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com