Julia 如何确定字典键的索引?

how Julia determines index of dictionary keys?

我在 Julia 的字典集合中遇到了奇怪的行为。字典可以在 Julia 中这样定义:

dictionary = Dict(1 => 77, 2 => 66, 3 => 1)

并且您可以使用 keys:

访问密钥
> keys(dictionary)

# [output] 
KeySet for a Dict{Int64, Int64} with 3 entries. Keys:
2
3
1

# now i want to make sure Julia consider above order. so i use collect and then i will call first element of it
> collect(keys(dictionary))[1]

# [output] 
2

如您所见,keys(dictionary) 输出中的键顺序非常奇怪。似乎 Julia 没有考虑输入中 (key=>value) 的顺序!即使它似乎没有按升序或降序排序。 Julia 如何为 keys(dictionary) 输出建立索引?


预期输出:

> keys(dictionary)

# [output] 
KeySet for a Dict{Int64, Int64} with 3 entries. Keys:
1
2
3

> collect(keys(dictionary))[1]

# [output] 
1

我希望 keys(dictionary) 按照我在定义 dictionary 时输入的顺序给我密钥。

Dict 中的按键顺序目前未定义(将来可能会更改)。

如果您希望保留顺序,请使用 OrderedDict from DataStructures.jl:

julia> using DataStructures

julia> dictionary = OrderedDict(1 => 77, 2 => 66, 3 => 1)
OrderedDict{Int64, Int64} with 3 entries:
  1 => 77
  2 => 66
  3 => 1

julia> keys(dictionary)
KeySet for a OrderedDict{Int64, Int64} with 3 entries. Keys:
  1
  2
  3

这不是 Julia 特有的,而是一个常见的 属性 词典,有时甚至合并到 definition thereof

A dictionary is an abstract data type that defines an unordered collection of data as a set of key-value pairs.

实现字典的最常见方法之一是 hash map / hash table, which is indeed the default implementation of Dictionaries in Julia。由于在散列映射中,对象存储在由键的散列确定的位置,因此元素存储的顺序极不可能与键的数字顺序匹配(如果确实,键甚至 数字)。

如果您想要一个类似于字典但顺序稳定的结构,您可以考虑 OrderedCollections.jl 中的 OrderedDict,或者甚至只是一个简单的命名元组:

julia> nt = (a = 77, b = 66, c = 1)
(a = 77, b = 66, c = 1)

julia> nt[1]
77

julia> nt[2]
66

julia> nt[3]
1

julia> nt.a
77