Values ​​and keys guaranteed in sequential order?

When applied to Dictwhether values(...)and keys(...)to return the items in the order of coincidence?

In other words, is it zip(keys(d), values(d))guaranteed to contain exactly the key-value pairs of the dictionary d?

+4
source share
4 answers

Option 1

Julia’s current source indicates that the keys and vals of the object Dict()are stored as Arrayobjects that are ordered, so you can simply use values()it keys()separately, as in the wording of the question. But it is dangerous to rely on hood implementation details that are not documented, as they are subject to change without notice.

Option 2

An OrderedDictfrom the package DataStructures(along with the functions values()and keys()) is probably the easiest and safest way to be sure of sequential ordering. This is normal if you do not need an order.

Option 3

DataStructures, Julia, , .

Mydict = Dict("a" => 1, "b" => 2, "c" => 1)

a = [(key, val) for (key, val) in Mydict]

zip(), , .

, , :

Keys = [key for (key, val) in Mydict]
Values = [val for (key, val) in Mydict]

a[idx][1] idx Keys, .

+6

:

julia> let
           d = [i => i^2 for i in 1:10_000]
           z = zip(keys(d), values(d))
           for (pair, tupl) in zip(d, z)
               @assert pair[1] == tupl[1] && pair[2] == tupl[2]
           end
           info("Success")
       end
INFO: Success

, .

(dict) # 16743:

. , . , , Dict - , .

. :

, ? , OrederedDict?

+3

, keys values . , , .

, , . , , , .

+2

imap Iterators :

using Iterators
d = Dict(1=>'a',2=>'b',3=>'c')

# keys iterator is `imap(first,d)`
julia> collect(imap(first,d))
3-element Array{Any,1}:
 2
 3
 1

# values iterator is `imap(last,d)`
julia> collect(imap(last,d))
3-element Array{Any,1}:
 'b'
 'c'
 'a'

. .

+1
source

Source: https://habr.com/ru/post/1651578/


All Articles