如何让下面词典接受整数类型?

原问题

How could we have initialized myphonebook so that it would accept integers as values?

myphonebook = Dict(“Jenny” => “867-5309”, “Ghostbusters” => “555-2368”)

julia> myphonebook = Dict("Jenny" => "867-5309", "Ghostbusters" => "555-2368")
Dict{String,String} with 2 entries:
  "Jenny"        => "867-5309"
  "Ghostbusters" => "555-2368"

没太懂,你这样初始化就会得到 Dict{String,String}
你是想要能这样 myphonebook["Jenny"] = 8675309 赋值?

可以弄个函数用来读写 myphonebook,在函数里转换一下输入。让它做合法性检验,再把整数转成字符串,也可以顺带加上 -.

flexible_phonebook=Dict("Jenny"=>8675309,"Ghostbusters"=>"555-2368"

实际上,这个问题是接上面的,上面能接受整数类型,现在想让

myphonebook = Dict("Jenny" => "867-5309", "Ghostbusters" => "555-2368")

也接受整数类型,不知应该怎么弄,这里还没讲到函数,应该可以不用函数

那就不给初始值,也就是都设为 Any

julia> myphonebook = Dict()
Dict{Any,Any} with 0 entries

julia> myphonebook["Jenny"] = 8675309
8675309

julia> myphonebook["Ghostbusters"] = "555-2368"
"555-2368"

julia> myphonebook
Dict{Any,Any} with 2 entries:
  "Jenny"        => 8675309
  "Ghostbusters" => "555-2368"

julia> myphonebook["Jenny"] = "8675309"
"8675309"

julia> myphonebook
Dict{Any,Any} with 2 entries:
  "Jenny"        => "8675309"
  "Ghostbusters" => "555-2368"

newmyphonebook = convert(Dict{String, Any}, myphonebook)
newmyphonebook[“Shi”] = 123456

是的 我解决了 还有一种方法是

myphonebook = Dict{String, Any}("Jenny" => "867-5309", "Ghostbusters" => "555-2368")

知道了 谢谢 才发现原来习题是有答案的:sweat_smile: