Skip to content

Commit

Permalink
dict docs: document that ordering of keys/values/pairs match iterate (#…
Browse files Browse the repository at this point in the history
…56842)

Fix #56841.

Currently the documentation states that keys(dict) and values(dict)
iterate in the same order. But it is not stated whether this is the same
order as that used by pairs(dict), or when looping, for (k,v) in dict.

This PR makes this guarantee explicit.
  • Loading branch information
cossio authored Dec 18, 2024
1 parent 522624c commit 796d823
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
12 changes: 8 additions & 4 deletions base/abstractdict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ Return an iterator over all keys in a dictionary.
When the keys are stored internally in a hash table,
as is the case for `Dict`,
the order in which they are returned may vary.
But `keys(a)` and `values(a)` both iterate `a` and
return the elements in the same order.
But `keys(a)`, `values(a)` and `pairs(a)` all iterate `a`
and return the elements in the same order.
# Examples
```jldoctest
Expand All @@ -114,8 +114,8 @@ Return an iterator over all values in a collection.
When the values are stored internally in a hash table,
as is the case for `Dict`,
the order in which they are returned may vary.
But `keys(a)` and `values(a)` both iterate `a` and
return the elements in the same order.
But `keys(a)`, `values(a)` and `pairs(a)` all iterate `a`
and return the elements in the same order.
# Examples
```jldoctest
Expand All @@ -138,6 +138,10 @@ values(a::AbstractDict) = ValueIterator(a)
Return an iterator over `key => value` pairs for any
collection that maps a set of keys to a set of values.
This includes arrays, where the keys are the array indices.
When the entries are stored internally in a hash table,
as is the case for `Dict`, the order in which they are returned may vary.
But `keys(a)`, `values(a)` and `pairs(a)` all iterate `a`
and return the elements in the same order.
# Examples
```jldoctest
Expand Down
7 changes: 7 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,13 @@ end
[v for (k, v) in d] == [d[x[1]] for (i, x) in enumerate(d)]
end

@testset "consistency of dict iteration order (issue #56841)" begin
dict = Dict(randn() => randn() for _ = 1:100)
@test all(zip(dict, keys(dict), values(dict), pairs(dict))) do (d, k, v, p)
d == p && first(d) == first(p) == k && last(d) == last(p) == v
end
end

@testset "generators, similar" begin
d = Dict(:a=>"a")
# TODO: restore when 0.7 deprecation is removed
Expand Down

0 comments on commit 796d823

Please sign in to comment.