考虑以下代码:
dog = (a=5, b=6, c=7)
frog = Dict(pairs(dog))
frog.keys
Run Code Online (Sandbox Code Playgroud)
返回:
16-element Vector{Symbol}:
:a
:b
#undef
#undef
#undef
#undef
#undef
#undef
#undef
:c
#undef
#undef
#undef
#undef
#undef
#undef
Run Code Online (Sandbox Code Playgroud)
现在,我很清楚要获取字典的键,标准方法是keys(frog),这确实做了正确的事情,但是keys字典的属性是什么,为什么这么奇怪?
因为Dict是哈希表。这些位置由键的哈希值以表大小为模确定,在本例中为 16:
julia> (((hash(:a) % Int) & (16-1)) + 1)
1
julia> (((hash(:b) % Int) & (16-1)) + 1)
2
julia> (((hash(:c) % Int) & (16-1)) + 1)
10
Run Code Online (Sandbox Code Playgroud)
但有一种特殊情况:
julia> dog = (a=5, b=6, f=7)
(a = 5, b = 6, f = 7)
julia> frog = Dict(pairs(dog))
Dict{Symbol, Int64} with 3 entries:
:a => 5
:b => 6
:f => 7
julia> frog.keys
16-element Vector{Symbol}:
:a
:b
:f
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
julia> (((hash(:f) % Int) & (16-1)) + 1)
1
Run Code Online (Sandbox Code Playgroud)
正如您现在所看到的:a,存在:f索引冲突,因此:f需要计算新索引(您可以在 Ashlin Harris 在问题评论中链接的代码中详细了解如何完成此操作)。